为什么输入流找不到 class 文件夹之外的文件

Why won't input stream find a file outside of the class folder

我想将输入流与文件 "NewFile.java" 一起使用,如果该文件与执行行动。但是一旦我移动,我就会得到空引用。

我试过使用绝对路径和相对路径,开头有或没有“/”。

InputStream in = getClass()
                .getResourceAsStream("NewFile.java");

当文件位于项目的根目录时,我想获取该文件。

getResourceAsStream() 并不是要打开文件系统中的任意文件,而是打开位于 java 包中的资源文件。所以名称“/com/foo/NewFile.java”会在包 "com.foo" 中查找 "NewFile.java"。您无法使用此方法打开包外的资源文件。

最好使用 InputStream in= new FileInputStream(new File("path/to/yourfile"));

您现在使用它的方式是作为必须位于 class 路径中的资源。

文件系统上的 files 和 class 路径上的 resources 是有区别的。通常,.java 源文件不会 copied/added 到 class 路径。

对于 class foo.bar.Baz 和资源 foo/bar/images/test.png 可以使用

Baz.class.getResourceAsStream("images/test.png")
Baz.class.getResourceAsStream("/foo/bar/images/test.png")

如您所见,路径是 class 路径 ,可能在 .jar 文件中。

使用文件系统路径:

Path path = Paths.get(".../src/main/java/foo/bar/Baz.java");
InputStream in = Files.newInputStream(path);
List<String> lines = Files.readAllLines(path);
List<String> lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1);
Files.copy(path, ...);