Java FileWriter 类 - java.io.FileNotFoundException : * no such file or directory -Ubuntu

标签 java ubuntu filewriter

我正在使用这种方法生成一些海龟文件 .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 似乎对此并不满意。

这是我迄今为止尝试过的:

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

  2. 使用绝对路径而不是相对路径,通过使用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/

相关文章:

java - Hibernate 更改某行代码得到明显的死锁

ubuntu - 无法加载元包列表 : [Errno 12] Cannot allocate memory

node.js - 找不到模块 'passport'

python - 尝试安装 python 模块时出现问题 : pyHook

Scala 在 while 循环内写入和读取文件

java - 为什么我的 ActionListener 只适用于我的一个按钮?

java - 行尾,FileWriter\n

java - 为什么自定义对象不是 HashMap 的等效键?

java - 画图程序麻烦java

java - 如何在其他线程上正确执行数据库调用?