我正在使用这种方法生成一些海龟文件 .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);
关于Java FileWriter 类 - java.io.FileNotFoundException : * no such file or directory -Ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59468997/