java - 我在 eclipse 项目目录中找不到我保存的文件

标签 java eclipse filepath

我无法找到正确写入的文件。我可以从中读取它,但是当我想在我的项目目录中找到它时,它不在那里......我尝试在我的所有计算机文件夹中搜索它,但它不在那里。仅当我包含绝对路径时,我才能在项目目录中找到它。

final String FILE_NAME = "test.dat";

//READ FILE
File readFile = new File(FILE_NAME);

if (readFile.exists()) {

System.out.println("file exsists...");
FileInputStream f_in = new FileInputStream(readFile);

   // Read object using ObjectInputStream
 ObjectInputStream obj_in = new ObjectInputStream(f_in);

// Read an object
   Object obj = null;

    try {
    obj = obj_in.readObject();
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
            e.printStackTrace();
     }

if (obj instanceof JsonObjectLoad) {

 jo = (JsonObjectLoad) obj;

  }
 obj_in.close();

}
else {
 jo = new JsonObjectLoad();

}

  jo.localities.add(loc);



//WRITE FILE
    File writeFile = new File(FILE_NAME);

    writeFile.createNewFile();

FileOutputStream f_out = new FileOutputStream(writeFile);

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new ObjectOutputStream(f_out);

// Write object out to disk
obj_out.writeObject(jo);
obj_out.close();

我在 C:\eclipse_ee\eclipse\test.dat 中找到了一个路径...我该如何更改它?

最佳答案

只需打印 absolute path检查它存在于哪里?仅当不存在时才创建新文件 exits否则它将取代现有的。

File writeFile = new File(FILE_NAME);
if(!writeFile.exists()){
    writeFile.createNewFile();
}
System.out.println(writeFile.getAbsolutePath());

注意:无需调用writeFile.createNewFile(),因为如果您开始写入的位置不存在FileOutputStream,它会自动创建一个新文件。

<小时/>

如果您想在文件已存在时以附加模式打开文件并且不想替换现有内容,请使用 FileOutputStream(File file,boolean append)构造函数并传递 true 作为附加参数。

<小时/>

使用相对于项目的src文件夹的路径:(尝试任何一个)

// file that exists under resources folder parallel to src in your project
File file1 = new File("resources/xyz.txt");
System.out.println(file1.getAbsolutePath());

// file that exists under src/resources folder
File file2 = new File(getClass().getResource("/resources/abc.txt").toURI());
System.out.println(file2.getAbsolutePath());

这是项目结构:

project root
           |
           |__src
           |    |
           |    |__resources
           |                |
           |                |__abc.txt
           |
           |__resources
                      |
                      |__xyz.txt    

关于java - 我在 eclipse 项目目录中找不到我保存的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969743/

相关文章:

java - 在 Eclipse 调试配置中将 -Dvar=value 参数放在哪里?

java - 保护桌面应用程序图像免受外部修改

java - 当 IN 子句超过 100 或 1000 时,NamedParameterJdbcTemplate 不起作用

java - 使用 PopupWindow 的 showAtLocation(View, int, int, int) 时遇到问题

Eclipse git checkout(又名,还原)

Java - 程序在 Eclipse 中完美运行,但在导出到可运行 jar 时似乎没有执行其预期任务

python - Excel 导入 - 由文件路径/文件名引起的错误

java - 有没有一种干净简单的方法可以使 Java OS 中的文件路径字符串不可知?

c++ - 将文本作为字符串发送与引号之间的文本之间的区别

java - 检查泛型java中的引用类型