我已经尝试了几种方法来使用Path实现文件的正确路径,但到目前为止还没有成功。我正在试着写/重写这个文件。
在代码片段中,我将显示到目前为止我已经尝试过的内容,但我似乎无法找到正确的路径。下面是我的包的层次结构示例
src
├── information
│ └── destination
│ └── (empty)
└── classpackage
└── MyClass.java我试图保持相对于项目本身的路径,这样任何人都可以编译它,并在项目包层次结构中的正确位置创建文件,无论他们将src文件夹放在哪里。
这是在MyClass.java内部
private static final File FILE = new File("/src/information/destination", "data.set");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsolutePath())); //doesn't work
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE)); //doesn't work
ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsoluteFile())); //doesn't work发布于 2019-03-28 09:20:30
您需要获取绝对路径,并使用它来引用您想要的文件。Java提供了FileSystem帮助。获取绝对路径后,添加您的文件的文件路径。
import java.io.ObjectInputStream;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.FileSystems;
class FileRead {
public static void main(String[] args) {
try {
String filePath =
FileSystems.getDefault().getPath(".").
toAbsolutePath()+"/Practice/Stack";
File file = new File(filePath,"test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}finally{}
}
}发布于 2019-03-28 09:39:50
您可以简单地将路径更改为。源/信息/目标
和文件路径,如

解决方案:
package classpackge;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class MyClass {
private static final File FILE = new File("src/information/destination", "data.set");
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream in =new FileInputStream(FILE.getAbsolutePath()); //doesn't work
in.close();
//ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE)); //doesn't work
//ObjectInputStream in = new ObjectInputStream(new FileInputStream(FILE.getAbsoluteFile())); //doesn't work
}
}https://stackoverflow.com/questions/55388295
复制相似问题