I would like to get a list of file contained in a directory which is in a jar package.
I have an "images" folder, within it I have an Images class that should load all images from that directory.
In the past i used the MyClass.class.getResourceAsStream("filename"); to read files, but how do I read a directory?
This is what I tried:
System.out.println(Images.class.getResource("").getPath());
System.out.println(new File(Images.class.getResource("").getPath()).listFiles());
I tried with Images.class.getResource because I have to work with File and there isn't a constructor that accepts an InputStream.
The code produces
file:/home/k55/Java/MyApp/dist/Package.jar!/MyApp/images/
null
So it is finding the folder which I want to list files from, but it is not able to list files.
I've read on other forums that in fact you can't use this method for folders in a jar archive, so how can I accomplish this?
Update: if possible, i would like to read files without having to use the ZipInputStream
You can't do that easily.
What you need to do:
Get the path of the jar file.
Images.class.getResource("/something/that/exists").getPath()
Strip "!/something/that/exists".
Use Zip File System to browse the Jar file.
It's a little bit of hacking.
Related
I am trying to read and parsed all the CSV files, these files are inside of extracted zip file, but unfortunately, I'm only getting this (No such file or directory) - How can I get inside that folder and read those files? Take note that this folder is already unzipped.
I'm also thinking, that if that is not possible - is there any way that I can extract the zip file to files only, for example below:
Zip File: ZipFolder.zip
Expected: (No folder at all, automatically the files is on the target location already).
CSVFile1.csv
CSVFile2.csv
Can someone help me to get through this? your help is appreaciated.. Thank you!
We are programming a game, which shall be startable from a .jar file. First we created a Project in IntelliJ and loaded the Images from a ZIP with the following code:
ZipFile zf = null;
try {
zf = new ZipFile(zipPath);
Image Image = ImageIO.read(zf.getInputStream(zf.getEntry("Block/Air.png")));
} catch (IOException ignored) {}
Now the attempt without the ZIP (just from the .jar) is:
Image image=ImageIO.read(getClass().getResourceAsStream(path+ "Block/Air.png"));
It doesn't load any texture. Do you have a better way to do this in combination?
Edit:Seems not to be the Problem.
Since jars are zip files you could place them in the jar file and placing them the classpath.
Image image=ImageIO.read(getClass().getResourceAsStream(path+ "Block/Air.png");
Path must be a relative path from a source path root. E.g. I have a file in "src/main/resource/my/cool/game/" path is "/my/cool/game".
If you want to use a zip file, it must be outside of your jar file. To load the zip, you could use a relative file path, which is the same if you start your game from Intellij and from dekstop.
To change the working directory in intellij look here.
The best way would be to place the zip file alongside the jar so you can use "." as working directory to load the zip file.
Alternatively you could use a fixed directory, but then your game needs some sort of installation so it knows where to finde the zip file.
If you use ".", the zip file needs to be in the root of the project directory.
The Class.getResource and Class.getResourceAsStream methods take a URL (not a file path!) which is relative to the root of each classpath entry. For classpath entries which are .jar files, this means the path of a file packaged within the respective .jar file.
If your entire program is in one .jar file, the classpath consists of just one item: that .jar file. Therefore, there is only one classpath root, and the String you pass to getResourceAsStream is the URL of an entry within your .jar file. Do not include the path to the .jar file in that String.
If you are not sure what you should pass, examine your .jar file's contents. Every IDE (that I know of) provides a way to do this. You can also use any unzip utility to examine a .jar file, since every .jar file is actually a .zip file. (If you only have Windows, with no zip tools installed, make a copy of the .jar file and change the copy's extension to ".zip", then open it.)
Inside the .jar file are, of course, zip entries. The full path of the entry you want to load (without the path to the .jar file) is what you must pass to getResourceAsStream. getResourceAsStream accepts a URL, and URLs always use forward slashes (/) on all platforms, so do not use any backslashes. Also, the first character of the String must be /.
It is actually possible to specify a shorter path, depending on how your images are packaged in the .jar, but that is a separate topic. See the documentation for full details.
Side note: Never, ever write an empty catch block. Ever. That caught exception is by far the easiest way for you or anyone else to know when and why your program is not working. At the very least, put exc.printStackTrace(); in your catch block. More often, the correct course of action is to abort the program with something like throw new RuntimeException(exc);. After all, your program can't continue to function properly if it can't load that image, right?
Why do you need to store your images in a zip file? If you're doing it to reduce the file size, you gain absolutely nothing from zipping it first. JAR files are zipped files anyway (if you don't believe me, rename your .jar file to .zip, and try to open it). What you're basically doing is attempting to zip an already zipped file, which doesn't really do anything.
I would recommend you unzip your images and store them somewhere like < resources >/images
If you insist on leaving them zipped, you'll need to change it to something like this. Otherwise, it's looking for the zip file in the working directory (directory from which the jar was executed)
ZipFile zf = new ZipFile(getClass().getResourcesAsStream("path/to/zip"));
Disclaimer: I am not familiar with the ZipFile class, so I do not know if that constructor exists.
I have a JAR file that I wanted to edit a string inside on of it's classes . So I extracted it using Winrar , done the changes I wanted and saved it . Now I have a folder with subfolders inside that contains class files (about 30 one) .My question here is how can I recreate the Jar file from those folders&files ? Like it's it's doing the reverse action of extracting the Jar file .. ?
You could create a .zip file, rename it (with WinRAR) to something.jar so it becomes a .jar archive and then copy the folders in there.
But what you are doing is not really recommended to be done
You shouldn't extract and re-archive it like that.
And DON'T I repeat DON'T edit .class files!
Jar file is basically a zip file - however the best way to edit jars is to use a file manager (like Total Commander). You can delete, copy, rename, ... whatever, transparently inside the archive.
http://en.wikipedia.org/wiki/JAR_%28file_format%29
May be only one tip for the Total Commander - to enter the archive just use Ctrl-Pagedown. And I don't think that is something wrong on jar editing (in some circumstances you have no other option). However class files editing... it is a different game ...
I am having problem to use JWNL wordnet in a Jar file.
JWNL uses RandomAccessFile to read wordnet dictionary files. In order to create a Jar file, wordnet dictionary files are put in resources/wordnet folder. As resources is in my Build Path, I have no problem to run the application I created in Eclipse. However, when I use another application to run the created jar file, I get the following error:
java.io.FileNotFoundException: resources/wordnet/data.noun (No such file or directory)
from the following code:
RandomAccess _file = new RandomAccessFile(path, _permissions);
I use the following code to check the current working directory:
URL location = PrincetonRandomAccessDictionaryFile.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
It seems both situation have the same location: /project/bin/
How should I fix the problem? Thank you
The key information you seem to be missing is that Jar files are compressed, and you can't "seek" because of the compression (which is I believe the DEFLATE algorithm).
However, you could extract the file(s) into temp file(s) on start and then use that. Temp files would be removed on application exit, and are the best answer I can think of.
RandomAccessFile to read files in a Jar file
There are no files in a JAR file. There are JAR entries. You can't read them with FileInputStreams, RandomAccessFiles, or FileReaders.You need to use a JarInputStream or its friends.
How would you read a file into a program that's compiled into a jar next to it through its local directory? The type read would be a simple .txt file.
It depends on what the usage of the program is. Do you know how the jar is supposed to be executed? When you try to run it, does it spit out a "usage: somejar firstarg secondarg" type message?
Also, if its a jar that you've compiled and you know how it should be executed, then you may have forgot to set its main class or manifest.
Check this: http://www.mkyong.com/java/how-to-make-an-executable-jar-file/
If you want to read a file that exists within an external .jar file, you will need to unzip the .jar file first in your code and then retrieve the file. You can do this using Java's zip APIs. See this answer if this is the case: Easiest way to unpack a jar in java
If you want to read a file that is in the same .jar file that your code is executing, you can get the file as a resource. See this answer: Get a resource using getResource()
If the file is simply in the exact same directory as the executable .jar, create a new file like so:
File input = new File("myfile.txt");