我在创建FileWriter时指定了文件位置的完整路径,但没有看到正在创建的文件。在创建文件的过程中,我也没有得到任何错误。
下面是我的代码片段:
public void writeToFile(String fullpath, String contents) {
File file = new File(fullpath, "contents.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(contents);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
完整路径为"D:/codes/sources/logs/../../bin/logs"
。我已经搜索了整个目录,但我在任何地方都找不到该文件。如果我只指定了filename only file File = new File("contents.txt");,它就能够保存文件的内容,但是它不会放在我喜欢的位置。
如何将文件内容保存到首选位置?
更新:我使用file.getAbsolutePath()打印了完整的路径,并且我得到了正确的目录路径。D:\codes\sources\logs....\bin\logs\contents.txt,但当我在目录中查找该文件时,我无法在那里找到它。
发布于 2013-07-18 16:49:59
确保在path参数中添加尾随反斜杠,以便将该路径识别为目录。提供的示例适用于使用已转义的反斜杠的Windows操作系统。要获得更健壮的方法,请使用系统的file.separator
属性。
Works
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
"this is a test");
不工作
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
"this is a test");
文件分隔符示例
String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
+ "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");
https://stackoverflow.com/questions/17718613
复制相似问题