Java代码无法从资源加载静态文件

时间:2018-07-14 10:00:22

标签: java maven

Java代码无法从资源文件夹加载静态文件

/etc/services-available/java/testFile.txt (No such file or directory)

我的代码:

InputStream testFileContent = this.getClass().getResourceAsStream(File.separator+"testFile.txt");

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(testFileContent));

1 个答案:

答案 0 :(得分:1)

资源是从类路径而不是文件系统中加载的。如果您有/src/main/resources/testFile.txt,则应加载getResourceAsStream("/testFile.txt")

要加载常规文件,请使用FileInputStreamFiles实用工具类:

Path path = Paths.get("/", "etc", "services-available", "java", "testFile.txt");
try (BufferedReader br = Files.newBufferedReader(path)) {
  ...
}