FileInputStream不适用于相对路径

Mah*_*amy 17 java filenotfoundexception fileinputstream

我试图从中创建一个对象FileInputStream并将文件的相对值传递给它的构造函数,但它无法正常工作并抛出一个FileNotFoundException

try {
   InputStream is = new FileInputStream("/files/somefile.txt");
} catch (FileNotFoundException ex) {
   System.out.println("File not found !");
}
Run Code Online (Sandbox Code Playgroud)

Duk*_*ing 42

/一开始会使得绝对路径,而不是相对的.

尝试删除前导/,所以替换:

InputStream is = new FileInputStream("/files/somefile.txt");
Run Code Online (Sandbox Code Playgroud)

有:

InputStream is = new FileInputStream("files/somefile.txt");
Run Code Online (Sandbox Code Playgroud)

如果您仍然遇到问题,请尝试通过检查当前目录来确保程序在您认为的位置运行:

System.out.println(System.getProperty("user.dir"));
Run Code Online (Sandbox Code Playgroud)

  • 否,如果文件与InputStream实例代码位于同一目录中,则该命令不起作用。 (2认同)

Mic*_*ael 7

其他海报是对的,你给出的路径不是相对路径.你可能会做类似的事情this.getClass().getResourceAsStream("Path relative to the current class").这将允许您基于相对于您调用它的类的路径将文件加载为流.

有关更多详细信息,请参阅Java API:http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)


Bac*_*ash 5

  1. 这不是相对路径,而是绝对路径。
  2. 如果您使用的是 Windows,则需要在路径之前添加驱动器号:

InputStream is = new FileInputStream("C:/files/somefile.txt");

windows 不支持/“root”符号

如果您想加载要放入 JAR 中的文件,则需要使用

getClass().getResource("path to your file");
Run Code Online (Sandbox Code Playgroud)

或者

getClass().getResourceAsStream("path to your file");
Run Code Online (Sandbox Code Playgroud)