[英]The system cannot find the path specified with FileWriter
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 ...
In general, a non existent file will be created by Java only if the parent directory exists. 通常,只有父目录存在时,Java才会创建不存在的文件。 You should check/create the directory tree:
您应该检查/创建目录树:
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);
You can use getParentFile
( Java Doc ) to make sure that the parent directory exists. 您可以使用
getParentFile
( Java Doc )来确保父目录存在。 The following will check that the parent directory exists, and create it if it doesn't. 以下将检查父目录是否存在,如果不存在则创建它。
File myFile = new File(fileName);
if(!myFile.getParentFile.exists()) {
myFile.getParentFile.mkdirs();
}
I'd guess that the "output" directory doesn't exist. 我猜测“输出”目录不存在。 Try adding:
尝试添加:
new File(System.getProperty("user.dir") + File.separator + "output").mkdir();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.