![](/img/trans.png)
[英]PrintWriter : java.io.FileNotFoundException: The system cannot find the path specified
[英]FileNotFoundException (The system cannot find the path specified)
我得到這個例外:
java.io.FileNotFoundException: C:\...\filename.xml (The system cannot find the path specified)
使用此代碼:
FileWriter fileWriter = new FileWriter(new File(path + date + time "filename.xml"));
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data");
存在路徑,但需要創建“日期”和“時間”的目錄。 應用程序對目錄具有完全權限。
有任何想法嗎?
問題是因為我正在創建一個用於編寫文件的子目錄。 所以我目前有
C:\\example\\
並想在C:\\example\\<date>\\<time>\\<files>
編寫我的文件
你需要在寫作之前調用File#mkdirs()
。
File file = new File("C:/example/newdir/newdir/filename.ext");
file.mkdirs();
// ...
假設計算機是對的,你錯了。
並且,在該場景中,您要寫入的目錄不會退出(或沒有權限執行此操作)。
System.getProperty("user.dir")
代碼對我有用。 (需要添加writer.close()
以顯示文件中的文本。)
您還需要將新創建的文件和文件夾路徑轉換為字符串。
File folder = new File("src\\main\\json\\", idNumber);
folder.mkdir();
if (!folder.exists()) {
try {
folder.createNewFile();
} catch (IOException ex) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex);
}
}
...
...
FileOutputStream output = null;
File file;
String content = data.toString();
try {
String folder_location = folder.toString() + "\\";
String filename = "CurrentInfo";
file = new File(folder_location + filename.toString() + ".json");
output = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] content_in_bytes = content.getBytes();
output.write(content_in_bytes);
output.flush();
output.close();
} catch (IOException ex) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
Logger.getLogger(JsonGeneration.class.getName()).log(Level.SEVERE, null, e);
}
}
}
什么對我有用:我的項目所在的文件夾名稱中有一個空格。 我用連字符( - )替換了空格。 現在,文件的相對路徑沒有空格(%20)。 這個改變對我有用。 希望它可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.