我有一个问题,就是找到写得正确的文件。我可以从它读取,但当我想在我的项目目录中找到它时它不存在..我试图在我的所有计算机文件夹中搜索它但它不在那里。只有当我包含apsolute路径时,我才会在项目目录中找到它。
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中找到了一条路径...如何更改?
答案 0 :(得分:1)
只需打印absolute path即可查看其存在位置?仅在不exits时创建新文件,否则它将替换现有文件。
File writeFile = new File(FILE_NAME);
if(!writeFile.exists()){
writeFile.createNewFile();
}
System.out.println(writeFile.getAbsolutePath());
注意:无需拨打writeFile.createNewFile()
,因为FileOutputStream
会自动创建一个新文件,如果您开始在其中书写的话。} p>
如果要在文件已存在且不想替换现有内容时以附加模式打开文件,请使用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