Reading a file into compiled jar by relative path - java

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

Related

unable to read config.properties in java with jar file

I'm new to java , i have file named config.porperties
i put it in this path /home/user/workspace/myproject/config.properties
but when i submitted the jar file after packaged it i got that it cannot find this file
java.io.FileNotFoundException: config.properties (No such file or directory)
the code
FileInputStream finputstream = new FileInputStream(
"/home/user/workspace/myproject/config.properties");
prop.load(finputstream);
but there is no error in the code i think the problem with jar file that it couldn't read the path !
Hope i can find help , THANKS
I am not sure what happend during "but when i submitted the jar file after packaged it". Your code still tried to load home/user/workspace/myproject/config.properties. So check whether that file exists and is readable.
If you want the file to reside on a different path - you have to change your code as the path is hardcoded.
if you expect the config.properties to be packaged within the jar and loaded from there, change your code to something like
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file/config.properties");
Watch out: Again you are hardcoding a path but you can ensure the file will reside at that location within the jar.

How do you load an Image from a ZIP file contained in a .jar file?

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.

File doesn't read after creating jar using netbeans

i have a small application which checks for values from a file and display the result in a jframe.
A file contain list of word to check. this file is placed in project folder "testing" and the main source testing.java file is present in location "testing\src\testing"
input file : c:\document..\netbeans\testing\
java file : c:\document..\netbeans\testing\src\testing\
when i place the input file inside folder "c:\document..\netbeans\testing\src\testing\
" the input file is not taken as input, it works only when kept on folder "c:\document..\netbeans\testing\"
so when a jar file is created it has not included the input file in that, even i manually input that is not taking the input file in and working.
some path setting issue? what can be done to solve this issue?
any help pls??
Once you create the jar, the file becomes an embedded resource. If you try to read it as a File it will no long be the same file system path as you originally use in the program. It must now be read from the class path.
To read the file from the class path, you will want to use getClass().getResourceAsStream(), which return an InputStream. If your file is in the same location (package) as your class file, then you should use
InputStream is = getClass().getResourceAsStream("input.txt");
Then you can read from the InputStream
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
This generally happens, when you don't use absolute path...!
As when you run your program from IDE(Netbeans) then the HOME_FOLDER is your ProjectFolder. Relative to which you would have given the file_path(that has to be accessed in your program).
But after building, jar is present in ProjectFolder/dist. When you run the jar file the HomeFolder is not ProjectFolder rather it is ProjectFolder/dist.
So, to make it successful, to need to copy all files and folders from ProjectFolder/dist to ProjectFolder.
Then run the jar.. Hope it will fix the issue
Try putting double backslashes in your file paths. Like this:
c:\\document..\\netbeans\\testing\\src\\testing\\
This is the format that java normally requires it to be in

JAR - Listing files into a folder

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.

Java - read file from directory for jar

I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).

Categories

Resources