FileInputStream doesn't work with the relative path [closed]

时光总嘲笑我的痴心妄想 提交于 2019-12-18 03:09:01

问题


I tried to create an object from FileInputStream and pass the relative value of a file to its constructor, but it doesn't work properly and threw a FileNotFoundException

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

回答1:


The / at the start will make the path absolute instead of relative.

Try removing the leading /, so replace:

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

with:

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

If you're still having trouble, try making sure the program is running from where you think by checking the current directory:

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



回答2:


The other posters are right the path you are giving is not a relative path. You could potentially do something like this.getClass().getResourceAsStream("Path relative to the current class"). This would allow you to load a file as a stream based on a path relative to the class from which you call it.

See the Java API for more details: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)




回答3:


  1. this is not a relative path, it is an absolute path.
  2. If you are on Windows you need to add your drive letter before your path:

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

windows doesn't support the / symbol as "root"

If you want to load a file thatt you'll put in your JAR, you need to use

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

or

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


来源:https://stackoverflow.com/questions/14553292/fileinputstream-doesnt-work-with-the-relative-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!