【问题标题】:I can't find my saved file in eclipse project directory我在 Eclipse 项目目录中找不到我保存的文件
【发布时间】:2014-07-26 09:50:11
【问题描述】:

我在查找写入正确的文件时遇到问题。我可以从中读取,但是当我想在我的项目目录中找到它时,它不存在..我试图在我所有的计算机文件夹中搜索它,但它不存在。只有当我包含绝对路径时,我才能在我的项目目录中找到它。

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 中找到了一个路径...如何更改它?

【问题讨论】:

  • 听起来很可疑。当您在 Eclipse 中运行程序时,它会从项目的根目录运行它。由于您没有提供任何路径,它将从当前目录(项目的根目录)或其类路径中读取。我建议检查项目的根目录以及您在构建路径中添加的所有类路径条目。尝试运行代码表单命令行。

标签: java eclipse filepath


【解决方案1】:

只需打印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    

【讨论】:

  • 我找到了一个路径...它保存在 C:\eclipse_ee\eclipse\serialize.dat 我该如何更改它?
  • 但文件 file1 = new File("resources/abc.txt");如何将它移动到我想要的位置?
猜你喜欢
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 2012-07-27
相关资源
最近更新 更多