Java 系统找不到 FileWriter 指定的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2898179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:15:22  来源:igfitidea点击:

The system cannot find the path specified with FileWriter

javafilewriterfile-not-found

提问by rfgamaral

I have this code:

我有这个代码:

private static void saveMetricsToCSV(String fileName, double[] metrics) {
        try {
            FileWriter fWriter = new FileWriter(
                    System.getProperty("user.dir") + "\output\" +
                    fileTimestamp + "_" + fileDBSize + "-" + fileName + ".csv"
            );

            BufferedWriter csvFile = new BufferedWriter(fWriter);

            for(int i = 0; i < 4; i++) {
                for(int j = 0; j < 5; j++) {
                    csvFile.write(String.format("%,10f;", metrics[i+j]));
                }

                csvFile.write(System.getProperty("line.separator"));
            }

            csvFile.close();
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }

But I get this error:

但我收到此错误:

C:\Users\Nazgulled\Documents\Workspace\Só Amigos\output\1274715228419_5000-List-ImportDatabase.csv (The system cannot find the path specified)

C:\Users\Nazgulled\Documents\Workspace\Só Amigos\output\1274715228419_5000-List-ImportDatabase.csv(系统找不到指定的路径)

Any idea why?

知道为什么吗?

I'm using NetBeans on Windows 7 if it matters...

如果重要的话,我在 Windows 7 上使用 NetBeans...

采纳答案by leonbloy

In general, a non existent file will be created by Java only if the parent directory exists. You should check/create the directory tree:

通常,只有父目录存在,Java 才会创建不存在的文件。您应该检查/创建目录树:

  String filenameFullNoPath = fileTimestamp + "_"  + fileDBSize + "-" 
        + fileName + ".csv";
  File myFile =  new File(System.getProperty("user.dir")  + File.separator 
        + "output" + File.separator + filenameFullNoPath);
  File parentDir = myFile.getParentFile();
  if(! parentDir.exists()) 
      parentDir.mkdirs(); // create parent dir and ancestors if necessary
  // FileWriter does not allow to specify charset, better use this:
  Writer w = new OutputStreamWriter(new FileOutputStream(myFile),charset);

回答by Brett Kail

I'd guess that the "output" directory doesn't exist. Try adding:

我猜想“输出”目录不存在。尝试添加:

new File(System.getProperty("user.dir") + File.separator + "output").mkdir();

回答by ems

You can use getParentFile(Java Doc) to make sure that the parent directory exists. The following will check that the parent directory exists, and create it if it doesn't.

您可以使用getParentFile( Java Doc) 来确保父目录存在。下面将检查父目录是否存在,如果不存在则创建它。

File myFile =  new File(fileName);
if(!myFile.getParentFile.exists()) {
     myFile.getParentFile.mkdirs();
}