FileInputStream不适用于相对路径

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

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

/在开始时将使路径绝对而不是相对。

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

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

有:

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

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

 System.out.println(System.getProperty("user.dir")); 

其他海报是对的,你给出的路径不是相对路径。 您可能会执行类似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)

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

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

windows不支持/符号为“root”

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

 getClass().getResource("path to your file"); 

要么

 getClass().getResourceAsStream("path to your file");