Access file in jar file?
I need to be able to access a file stored in a compiled jar file. I have figured开发者_开发知识库 out how to add the file to the project, but how would I reference it in the code? How might I copy a file from the jar file to a location on the user's hard drive? I know there are dozens of ways to access a file (FileInputStream, FileReader, ect.), but I don't know how to look inside itself.
You could use something like this:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileFromJarFile);
If foo.txt was in the root of your JAR file, you'd use:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("foo.txt");
assumes the class is in the same JAR file as the resource, I believe.
You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead.
For example:
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("foo.txt")));
You could read the contents of a JAR file using the JarFile class.
Here's an example of how you could get a specific file from a JAR file and extract it:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}
Just wanted to add that if we want to access file inside Jar that is located at the following path(only examples as resources loading is OS independent):
Windows:
c:\your-jar-file.jar\dir1\dir2\dir3\foo.txt
Linux:
/home/your-jar-file.jar/dir1/dir2/dir3/foo.txt
Will need to use following code(pay attention that there is NO "/"(forward-slash) character in the beginning of the path):
InputStream is = this.getClass().getClassLoader().getResourceAsStream("dir1/dir2/dir3/foo.txt");
Look at the JarFile class. Everything you need to get the InputStream of a specific entry in the jar file is there.
精彩评论