我正在使用此方法在我的项目的子目录中生成一些乌龟文件.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();
}
}
但是当我将我的项目放在Java类FileWriter
中的Ubuntu中(在Windows中仍然可以正常工作时,我遇到了这个异常:
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
以简化答案