How to access file inside JAR file as a string - java

I packaged some classes and libraries into a single JAR file. But the current code cannot access the files inside the JAR file as it is.
String scenarioFile = "netlogo/Altruism.nlogo";
// InputStream is = this.getClass().getResourceAsStream(scenarioFile);
simulator = HeadlessWorkspace.newInstance();
simulator.open(scenarioFile);
the .open expects a string but i read that i need to use inputstream format thus its not working. Is there any other workaround?

With the help of Tunaki i was able to get a way about doing it and it worked!
what i did was download commons.io.jar file
import org.apache.commons.io.*;
and then use an inputstream to read the file and then convert it to a string and use openFromSource method that Tunaki suggested of HeadlessWorkspace package to read it.
InputStream is = this.getClass().getResourceAsStream(NetlogoFile);
String scenarioFile = IOUtils.toString(is, "UTF-8");
simulator = HeadlessWorkspace.newInstance();
simulator.openFromSource(scenarioFile);

Related

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

Load file dynamically from jar

I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.

How to load a text file from a runnable jar

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.

How can I find the file containing a specific class somewhere in my classpath?

I'm trying to find a single file in classpath. This file is somewhere in one of JARs available in classpath. I'm sure that this task is rather typical. Is there any utility for this?
Try
URL url = getClass().getClassLoader().getReource("name");
or
InputStream is = getClass().getClassLoader().getResourceAsStream("name");
Combined with IOUtils
String text = IOUtils.toString(is);
byte[] bytes = IOUtils.toByteArray(is);
You can use this class, it looks for class files, but you can easily modify to look for all kind of files.

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