Java FileWriter类-java.io.FileNotFoundException:*没有这样的文件或目录-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();
        }
    }

但是当我将我的项目放在Java类FileWriter中的Ubuntu中(在Windows中仍然可以正常工作)时,我遇到了这个异常:

java.io.FileNotFoundException: /WWW/KG1/2/0.ttl (No such file or directory)

我在两个操作系统上都使用eclipse Neon,但是Ubuntu对此并不满意。

这是我到目前为止尝试过的:

  1. 在主项目目录下的所有文件和目录中添加写权限

  2. 使用绝对路径而不是相对路径,方法是使用System.getProperty("usr.dir"),并绘制我要提供给FileWriter的所有路径字符串,但是它不起作用。

有什么建议吗?

谢谢!

chunbaise0601 回答:Java FileWriter类-java.io.FileNotFoundException:*没有这样的文件或目录-Ubuntu

我将尝试使用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,以简化答案

本文链接:https://www.f2er.com/2866999.html

大家都在问