How to load a text file from a runnable jar - java

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

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"?
...

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.

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.

Related

In what situation is a file placed in the resources of a JAR, but is not accessible in a class' ClassLoader?

I'm just trying to read in a simple .txt file into my java project using this.class.getResourceAsStream(filename). I have several files within main/resources, and almost all of them return an object when I try to get them as an input stream. The only object I can't read in is my text file.
I have placed the file with all of the other resource files that are readable by the classloader, but it appears this file wasn't placed in the class' classLoader for whatever reason. If I unzip the jar, the file is still included with the jar in the same directory as all of the other resources, so it seems to be being built correctly.
I guess what I'm asking is at what point do I tell Java what files I want to be included as a resource in a class' ClassLoader? Is it something that should be done when the jar is built if things are in the correct place (i.e main/resources)?
Here is what the code looks like, and it's respective return values, when running for the file it can find and the file it can't, that are both located in the same place.
// This is not found. Both are placed at src/main/resources
def tmpDict = this.class.getResourceAsStream("dict.txt")
println tmpDict // null
// This is found
def tmpDict2 = this.class.getResourceAsStream("calc.config")
println tmpDict2 // sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream#2dae5a79
Without more info i'd say the path is wrong. when i used just "file.txt" for the path it got NPE
i used this method to read from the stream. The file was located at \src\main\resources\static\file.txt
This worked in eclipse, packaged into jar and worked there too.
public String getFile() throws Exception {
InputStream in = Controller.class.getClassLoader().getResourceAsStream("static/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
return out.toString();
}
Some very Basic checks:
The file must be case-sensitive (as it is not a Windows file), and special characters of the file name might be cumbersome. Also check that the file in your project has the file extension not twice (.txt.txt - Windows hiding the extension).
Check that getResourceAsStream("/a/b/c/A.txt") indeed gives a null.
If not the reading might go wrong on the encoding.

How to read a file that i created inside my the same package?

This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);

Robovm Read and write to a file

I try to write a text to a file and read this text later. When I use FileWriter I become a NullPointerException?
Is that a permission problem or ...? I also try the PrintWriter but I see the same Exception
.
This my code:
FileWriter fw = new FileWriter(new File("file.file"));
fw.write("XYZ");
best regards
londi
I guess your problem is that you use a relative file path, but that the origin of the relative path is not the one you think.
First of all, try to use an absolute path, that would be, on linux-like machines something like /home/me/myCode/myfile.txt or on windows something like c:/some/path/myfile.txt
Another thing you can do, in order to know what happens is print the origin.
File origin = new File(".");
System.out.println(origin.getAbsolutePath());
Once you know where the origin is, you can see what you need in order to get to your file.
Hope it will help.
Sounds like a permission issue. On iOS your application lives within a security sandbox, so you cannot just randomly read and write files anywhere you want. You could either use File.createTempFile to create a temp file somewhere hidden you your sandbox where nothing else can see it, or use the native api to determine where to dump your files. The following example will give you a file reference to the Documents Directory folder:
NSArray nsa = NSFileManager.defaultManager().URLsForDirectory$inDomains$(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask);
NSURL nsu = (NSURL)nsa.getFirst();
String snsu = nsu.getAbsoluteString() + "MyNewDocument.pdf";
File newFile = new File(new URI(snsu));

Create File object of file from parent directory in java

I have this issue of accessing a file in one of the parent directories.
To explain, consider the following dir structure:-
C:/Workspace/Appl/src/org/abc/bm/TestFile.xml
C:/Workspace/Appl/src/org/abc/bm/tests/CheckTest.java
In the CheckTest.java I want to create a File instance for the TestFile.xml
public class Check {
public void checkMethod() {
File f = new File({filePath value I want to determine}, "TestFile.xml");
}
}
I tried a few things with getAbsolutePath() and the getParent() etc but was getting a bit complicated and frankly I think I messed it up.
The reason I don't want to use "C:/Workspace/Appl/src/org/abc/bm" while creating the File instance is because the C:/Workspace/Appl is not fixed and in all circumstances will be different at runtime and basically I don't want to hard-code.
What could be the easiest and cleaner way to achieve this ?
Thank you.
You should load it from Classpath in this case.
In your CheckTest.java, try
FileInputStream fileIs = new FileInputStream(CheckTest.class.getClassLoader().getResourceAsStream("org/abc/bm/TestFile.xml");
Use System.getProperty to get the base dir or you set the base.dir during application launch
java -Dbase.dir=c:\User\pkg
System.getProperty("base.dir");
and use
System.getProperty("file.separator");
What could be the easiest and cleaner way to achieve this ?
For accessing static resources use:
URL urlToResource = this.getClasS().getResource("path/to/the.resource");
If the resource is expected to change, write it to a sub-directory of user.home, where it is easy to locate later.
First of all, you can't get a reference to the source file path on runtime.
But, you can access the resrources included at your classpath (where you complied .class files will be).
Normally, your compiler will copy the xml file included at your srouce directory into the build directory, so at last, you could end up having something like this:
C:/Workspace/Appl/classes/org/abc/bm/TestFile.xml
C:/Workspace/Appl/classes/org/abc/bm/tests/CheckTest.class
Then, with your classpath pointing to the compiled classes root dir, you get the resources from this directory, using the ClassLoader.getResource method (or the equivalent Class.getResource() method).
public class Check {
public void checkMethod() {
java.net.URL fileURL=this.getClass().getResource("/org/abc/bm/tests/TestFile.xml");
File f=new File( fileURL.toURI());
}
}
One could do this:
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File file = new File(pathOfTheCurrentClass + "/..", "Testfile.xml");
or
String pathOfTheCurrentClass = this.getClass().getResource(".").getPath();
File filePath = new File(pathOfTheCurrentClass);
File file = new File(filePath.getParent(), "Testfile.xml");
But as Tomas Naros points out this gives you the file located in the build path.
Did you try
URL some=Test.class.getClass().getClassLoader().getResource("org/abc/bm/TestFile.xml");
File file = new File(some.getFile());

Reading File In JAR using Relative Path

I have some text configuration file that need to be read by my program. My current code is:
protected File getConfigFile() {
URL url = getClass().getResource("wof.txt");
return new File(url.getFile().replaceAll("%20", " "));
}
This works when I run it locally in eclipse, though I did have to do that hack to deal with the space in the path name. The config file is in the same package as the method above. However, when I export the application as a jar I am having problems with it. The jar exists on a shared, mapped network drive Z:. When I run the application from command line I get this error:
java.io.FileNotFoundException: file:\Z:\apps\jar\apps.jar!\vp\fsm\configs\wof.txt
How can I get this working? I just want to tell java to read a file in the same directory as the current class.
Thanks,
Jonah
When the file is inside a jar, you can't use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you with openStream() the possibility to read the contents.
Or you can shortcut this by using getResourceAsStream() instead of getResource().
To get a BufferedReader (which is easier to use, as it has a readLine() method), use the usual stream-wrapping:
InputStream configStream = getClass().getResourceAsStream("wof.txt");
BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8"));
Instead of "UTF-8" use the encoding actually used by the file (i.e. which you used in the editor).
Another point: Even if you only have file: URIs, you should not do the URL to File-conversion yourself, instead use new File(url.toURI()). This works for other problematic characters as well.

Categories