
Untitled
By: a guest on
May 29th, 2012 | syntax:
None | size: 2.11 KB | hits: 12 | expires: Never
How to get a file from jar?
public class Test {
public static void main(String[] args) {
InputStream stream = Test.class.getResourceAsStream("/test.txt");
Scanner s = new Scanner(stream);
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
import java.io.*;
import java.util.zip.*;
public class UnZip {
final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(argv[0]);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " +entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
FileOutputStream fos = new FileOutputStream(entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private String getFile(File jar, String requestedFile) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream(); //change ouptut stream as required
ZipInputStream in = null;
try {
in = new ZipInputStream(new FileInputStream(jar));
ZipEntry entry;
while((entry = in.getNextEntry())!=null){
if (entry.getName().equals(requestedFile)){
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
} finally {
if (in!=null){
in.close();
}
out.close();
}
return new String(out.toByteArray());
}
META-INF/MANIFEST.MF
images/pic.gif
files/abc.txt
files/xxx.txt
jar xf yyy.jar files/xxx.txt