FileInputStream不适用于相对路径

时间:2013-01-27 22:55:27

标签: java filenotfoundexception fileinputstream

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

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

3 个答案:

答案 0 :(得分:38)

开头的/会使路径成为绝对路径而非相对路径。

尝试删除前导/,因此请替换:

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

使用:

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

如果您仍遇到问题,请尝试通过checking the current directory确保程序正在您所在的位置运行:

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

答案 1 :(得分:5)

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

答案 2 :(得分:2)

  1. 这不是相对路径,而是绝对路径。
  2. 如果您使用的是Windows,则需要在路径前添加驱动器号:
  3. InputStream is = new FileInputStream("C:/files/somefile.txt");

    windows不支持将/符号作为“root”

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

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

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