How can I get files in .jar file using java? - java

My problem is getting some CSS files from a foo.jar file. How can I get these CSS files from foo.jar? I found some ways, firstly by unzipping this .jar and copying files and then by deleting the unzipped folder. Is that a good way?

My JAR file location is C:\foo.jar
public static void main(String[] args) throws IOException {
{
URL url = getClass().getClassLoader().getResource("css/demo.css");
URL url2 = getClass().getClassLoader().getResource("");
System.out.println("url = " + url);
System.out.println("url_2 = " + url2);
}
}
Output:
url = jar:file:/C:/foo.jar!/css/demo.css
url_2 = file:/C:/
So, I don't need to extract foo.jar. I can copy files within JAR like this way. Thank you.

The following example will make you clear
Let's extract some files from the TicTacToe JAR file we've been using in previous sections. Recall that the contents of TicTacToe.jar are:
META-INF/MANIFEST.MF
TicTacToe.class
TicTacToe.class
TicTacToe.java
audio/
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au
example1.html
images/
images/cross.gif
images/not.gif
Suppose you want to extract the TicTacToe class file and the cross.gif image file. To do so, you can use this command:
jar xf TicTacToe.jar TicTacToe.class images/cross.gif
This command does two things:
It places a copy of TicTacToe.class in the current directory.
It creates the directory images, if it doesn't already exist, and places a copy of cross.gif within it.
The original TicTacToe JAR file remains unchanged.
As many files as desired can be extracted from the JAR file in the same way. When the command doesn't specify which files to extract, the Jar tool extracts all files in the archive. For example, you can extract all the files in the TicTacToe archive by using this command:
jar xf TicTacToe.jar

Put that jar into the class path of the project. Then you can access the resources you needed.

The basic command to use for extracting the contents of a JAR file is:
jar xf myjarfile.jar;
for more info please check this link out :
http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html
Hope this will help.

Related

File only accessible when placed in a location where it will be erased from the jar

I'm new to NetBeans IDE, and am struggling with accessing a file after building the jar file. After reading through many posts on this topic, I decided to try the following code:
BufferedReader read = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/file.txt")));
This works fine when my file is placed inside the "build" folder of the project where the .class files are, but of course this is a problem because it is erased in the "clean and build" process when the jar file is created. I have tried placing it in the src folder, in a separate "resources" package, and in the root of directory. I have also tried calling getResourceAsStream() with "file.txt" and "/src/file.txt," but it only works in the above configuration when the file is with the .class files. Any tips would be much appreciated!
Why not have your file folder inside the tomcat bin and refer the directory from your code. So maven clean will not alter the files and you can remove, update file without needing to restart the application. ( here i have file inside etc )
Path: /Users/username/Documents/apache-tomcat-8.5.15/bin/etc
ArrayList<String> readList = null;
String workingDir = System.getProperty("user.dir");
String fileName = "File.txt";
File file = new File(workingDir+"/etc/" + fileName);
readList = resourceReader.readFile(file.getAbsolutePath());
I have method readFile to parse some data and build the ArrayList in the above example.
Read about System Properties
Turns out the solution was really simple...I had been trying to manually create a resources folder, but the contents kept being deleted upon building of the jar. Instead, I created a resources package and put the file into the auto-generated folder inside the src folder, which packaged the file into the jar. Thanks everyone!

text file inside class folder, yet cannot find it

As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.
What I am trying to do is import it into an array, but the error is clear, no such file or directory.
You can try getting the path of the root folder from System.getProperty(). Then just append underlying folder names till the required filename.
private static String CLASS_PATH = System.getProperty("user.dir");
public static String FILE_PATH= CLASS_PATH + File.separator + "Source Packages"+ File.separator + "javaapplication2"+ File.separator + "pedidos.txt";
You should place files that are needed by your program in the classpath of your application so that they will get packaged in your JAR file. You can then read them with getResourceAsStream() Here's an idea of how that would work.
public class ArrayMain {
public static void main(String[] args) {
Scanner in = new Scanner(ArrayMain.class.getResourceAsStream("numbers.txt"));
String[] numbers = in.nextLine().split(",");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
The file numbers.txt is a simple file that looks like this:
1,2,3,4,5,6,7,8,9
Do not use relative paths to get files packaged with your application, it's dirty and senseless.
Path are relative to the folder in which was launched the java process. It's (usually) not your application source directory and never you file.java directory.
Even then, it's a terrible practice to put files (resources) inside your application source code. Because your java files needs to be compilated (and often packaged into a jar), the current architecture is likely to have no more meaning once packaged.
If you want to refer to a file on your computer, put it in a sensible folder (like /user/documents) and get it with its absolute path.
If you want the file to be packaged with your application, put it in a resource folder, package it in a jar and get the path with a classpath:// scheme.
The file needs to be placed at the root folder of your project.

Reading file right outside jar

So I have a .jar file in a folder and I have some input files in that folder. However, the program looks for the file in the home folder (several layers up). I want it obviously to read it from the folder that it's in but I don't want to be explicit about the file path to my folder because other people won't necessarily put their .jar file in the same spot.
Is there a way to read a file directly outside of the jar file? If not, is there a way to do this without hard-coding the file path?
edit:
here's the code. It just checks if the input files exist.
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by chris on 12/1/15.
* Control class that will be run when the jar is run.
*/
public class run {
public static void main(String[] args) throws Exception {
if (!(new File("settings.txt").exists())) {
start.run();
}
if (!(new File("api_key.txt").exists())) {
alert.display("Make your api_key.txt please.");
} else {
gatherData.run();
}
}
}
edit 2:
I've tried adding relative references with "./" at the beginning but that doesn't work either.
If you can rely on your .jar file being on the file system, you can get the absolute path of it by
new File(run.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
which can result in a SecurityException if a SecurityManager is present and not allowing this.
Another possibility would be to use
(new File(System.getProperty("java.class.path"))).getAbsolutePath();
The folder of the jar file can then be obtained using getParentFile()
If I am not wrong you are trying to access a file right in the same folder as that of the .jar file.
This can easily be done using the relative URL. By relative URL, I meant using
new File("./settings.txt"), this searches for the file in the folder same as that of the running .jar file. however you can use "../settings.txt" to look for the file one folder up.
"./" refers same directory "../" refers one directory up.
Just use ./ before file names.
The JAR files not neccesarly load from file system, and when loaded from file system can be any directory where the application start from - so relative path is not a good idea. The JAR files can from other types of source not only FileSystem, because it can be stream. I think the best way if there is a system parameter where you can pass the directory or working directory when you start the JAR file.

eclipse create jar file with txt file that can be referred to

I have a project in eclipse
foo_project
- src
- bar_package
bam.java
info.txt
- info.txt
- resources
- info.txt
In bam.java, say, I print the content of info.txt out like
try {
welcome = new BufferedReader(new FileReader("src/info.txt"));
String currentLine = null;
while ( (currentLine = welcome.readLine()) != null) {
System.out.println(currentLine);
}
welcome.close();
} catch (Exception fof) {
System.err.println(fof.toString());
}
It is working inside eclipse as it is when I put info.txt under src folder, however, it doesn't work once I export this project to a JAR file.
In the code, I tried just "info.txt" as well as "src/info.txt", none of them is working! As you can see, I put info.txt pretty much everywhere and not successful!
How can I refer to this info.txt in the Java code, and make Java find it at both inside eclipse and JAR file?
If the text in your info.txt will always be the same, instead of treating the text as a file, consider treating it as a "resource". If you do that , you can include it within your JAR, instead of having to distribute it as a separate file.
You open an InputStream to a resource using the Class.getResourceAsStream() method.
I think to load files from Jar file the file reader method will not work effectively, you will have to use class.getResource() or class.getResourceAsStream() methods
some helpful links,
Load a resource contained in a jar
How to load resource from jar file packaged in a war file?
Load resource from class's own JAR file
Also as others have suggested make sure the Jar file contains the txt file you looking for, you can either use "jar" command or winRAR
To access resources inside a JAR file, you need to use
YourClass.getClassLoader().getResourceAsStream("info.txt")
This way it will look inside the JAR file (or rather, in all places on the classpath) for the file as a Resource. It will work in both Eclipse and when packaged as a JAR.
I ended up using in the class
getClass().getResourceAsStream( "/info.txt") which gives an InputStream
Then I use InputStreamReader and BufferedReader to read out the file.
/ here is the src folder. Everything under this folder will be built to bin folder at the end.
If you have multiple source folders (a folder can be set to be source folder by right click and choose that option in Eclipse), all source folders built to single bin folder
For example,
if you have source folders
sourceA
foo_package/...
sourceB
bar_package/...
then in bin, it will be
bin (this is the "/")
foo_package/...
bar_package/...
Thanks for all the answers and inspiration to all!
you must put your txt file next to the jar file in your jar folder
it means that copy your txt file into your jar file folder not into jar file

Access a file from a JAR in the same folder

I need to acces (create and read) a file from a JAR file (executable jar),
and that file should be created in the same directory as the JAR
I tried
this.getClass().getResource("myFile")
but since the jar has packages in it, it won't work..
I also tried write just
File f = new File("myFile");
f.createNewFile();
and that works if i execute the JAR from the terminal, but if i execute the JAR by double-clicking it, the file is created in my home directory -.-''
how do i access a file being SURE that that file is in the SAME directory as the JAR file?
(of course also getting the jar absolute path would do the trick since i can get the parent folder from it)
This will give you the full path to the Jar:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
EDIT: sorry, was in javascript mode when I wrote that :). As was so politely requested, in a static method you should be able to do this:
String path = Me.class.getProtectionDomain().getCodeSource().getLocation().getPath();
(where the class name is Me).

Categories