user843337
user843337

Reputation:

Issues using getResource() with txt file (Java)

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)

Upvotes: 1

Views: 2779

Answers (4)

Andrew Thompson
Andrew Thompson

Reputation: 168825

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.

Upvotes: 1

user1254203
user1254203

Reputation:

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.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500535

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().

Upvotes: 3

MByD
MByD

Reputation: 137322

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();

Upvotes: 1

Related Questions