![](/img/trans.png)
[英]java.io.FileNotFoundException when opening file with filewriter in Java
[英]Java FileWriter class - java.io.FileNotFoundException: * no such file or directory -Ubuntu
我正在使用這種方法在我的項目的子目錄中生成一些海龜文件.ttl
:
public static void write(int id, int depth){
try {
FileWriter fw = null;
switch (getName()){
case ("KG1"):
fw = new FileWriter("WWW/KG1/" + depth + "/" + id + ".ttl");
break;
case ("KG2"):
fw = new FileWriter("WWW/KG2/" + depth + "/" + id + ".ttl");
}
// Write something
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
但是當我將我的項目放在 Ubuntu 中(它在 Windows 中仍然可以正常工作)的 java 類FileWriter
時,我遇到了這個異常:
java.io.FileNotFoundException: /WWW/KG1/2/0.ttl (No such file or directory)
我在兩個操作系統上都使用 Eclipse Neon,但 Ubuntu 似乎對此並不滿意。
這是我迄今為止嘗試過的:
為項目主目錄下的所有文件和目錄添加寫權限
使用絕對路徑而不是相對路徑,通過使用System.getProperty("usr.dir")
,並繪制我提供給FileWriter
所有路徑字符串,但它不起作用。
有什么建議嗎?
謝謝!
我會嘗試使用 File.separator 並確保父目錄存在。 這是一個示例(可能有語法問題)。
final String WWW = "WWW";
final String KG1 = "KG1";
final String KG2 = "KG2";
final String extension = ".ttl";
int id = 1;
int depth = 1;
String filePath = "." // current dir
+ File.separator
+ WWW
+ File.separator
+ KG1
+ File.separator
+ depth
+ File.separator
+ id
+ extension;
File file = new File(filePath);
// make sure parent dir exists (else created)
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
您可以通過使用 Path 和 File 對象讓事情變得更容易。 這是一個版本,如果它不存在,可以選擇創建想要的目錄
Path path = Paths.get("WWW", "KG1", String.valueOf(depth));
try {
Files.createDirectories(path);
FileWriter fw = new FileWriter(new File(path.toFile(), id + ".ttl"));
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
請注意,我故意跳過switch
以簡化答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.