Reputation: 5398
If i have a project which has a text file inside of it and i want to be able to read this text file which will be stored in my runnable jar then how can i do this? Currently i have a setup like this
public void someMethod()
{
File f = new File("aFileInEclipseResourcesFolder.txt");
doSomethingWithFile(f);
}
private void doSomethingWithFile(File f)
{
//print the data in the file;
}
The issue is the application cant locate the file if i use this approach but if i use a hard coded path to the file then it works. I know you can use getClass().getResourceAsStream()
but this wont allow me to get the already written file in to a file object without rewriting it again, or is this assumption incorrect?
Regards
Upvotes: 1
Views: 1100
Reputation: 109547
The getResourceAsStream delivers an InputStream you can use, just as a FileInputStream. You then can use:
InputStream is = getClass().getResourceAsStream("a/b/c/aFileInEclipseResourcesFolder.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); // Or "Cp1252"?
...
Upvotes: 1
Reputation: 7518
You don't want to use getResourceAsStream() you want
public URL getResource(String name)
the URL will give you the path to the resource and you can create a File object from that.
Upvotes: 0
Reputation: 4328
When I had this problem around a year ago the only solution I found was finding the location of the jar file (which is actually just a zip file), going through it and finding the file I wanted.
There are better methods around but they never worked for me (go figure), so keep this as a last resort.
Upvotes: 0