Issues using getResource() with txt file (Java)

这一生的挚爱 提交于 2020-01-15 11:32:09

问题


I have a setup in which I make use of a txt file (both reading and writing to it) in my program. At present I have it setup such that I use the local filepath on my machine, however I need to package it up into an executable JAR. To do this I've tried switching the filepath string over to the following:

String filepath = MyClass.class.getResource("/resources/textfile.txt");

However, when I run this I get a bunch of errors. After googling the method I found the similar method getResourceAsStream which I have also tried. This seems to return an InputStream object, however I need the filepath as a string ideally. Is this possible? If not what are my options?

Additional Info:

Here are the error messages I receive when trying to read & write to the txt file:

java.io.FileNotFoundException:/Users/Fred/Documents/Eclipse%20Projects/RandomProject/bin/resources/textfile.txt (No such file or directory)

回答1:


Well the code you've given won't compile, because Class.getResource returns a URL, not a String. You can't treat the resource as "just another file" - because it's not.

You should basically change whatever needs to read the file to accept an InputStream instead of a filename, and then pass in the result of calling getResourceAsStream().




回答2:


The method returns URL, not String. It's signature is public URL getResource(String name)

You might want to do:

String filepath = MyClass.class.getResource("/resources/textfile.txt").getPath();



回答3:


I have a setup in which I make use of a txt file (both reading and writing to it) in my program.

For read only, the resource can be in a Jar on the application class-path. It is very rare (in production) for resources on the application class-path to be writable. This text file will most probably need to be put in a reproducible path (e.g. a sub-directory of user.home - where the sub-dir is based on the package name) and used as a File from that path.

Or to put that a different way. I think you are pursuing the wrong path, to achieve the goal.




回答4:


If you expect to directly write to a text file inside a JAR, my friend then you are wrong all the way! Please post some more code for us to understand what is it exactly you want to achieve and how you think it could be done.



来源:https://stackoverflow.com/questions/9707892/issues-using-getresource-with-txt-file-java

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