Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 29th, 2012  |  syntax: None  |  size: 2.11 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to get a file from jar?
  2. public class Test {
  3.     public static void main(String[] args) {
  4.         InputStream stream = Test.class.getResourceAsStream("/test.txt");
  5.         Scanner s = new Scanner(stream);
  6.         while (s.hasNext()) {
  7.             System.out.println(s.next());
  8.         }
  9.     }
  10. }
  11.        
  12. import java.io.*;
  13. import java.util.zip.*;
  14.  
  15. public class UnZip {
  16.    final int BUFFER = 2048;
  17.    public static void main (String argv[]) {
  18.       try {
  19.          BufferedOutputStream dest = null;
  20.          FileInputStream fis = new FileInputStream(argv[0]);
  21.          ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
  22.          ZipEntry entry;
  23.          while((entry = zis.getNextEntry()) != null) {
  24.             System.out.println("Extracting: " +entry);
  25.             int count;
  26.             byte data[] = new byte[BUFFER];
  27.             // write the files to the disk
  28.             FileOutputStream fos = new FileOutputStream(entry.getName());
  29.             dest = new BufferedOutputStream(fos, BUFFER);
  30.             while ((count = zis.read(data, 0, BUFFER)) != -1) {
  31.                dest.write(data, 0, count);
  32.             }
  33.             dest.flush();
  34.             dest.close();
  35.          }
  36.          zis.close();
  37.       } catch(Exception e) {
  38.          e.printStackTrace();
  39.       }
  40.    }
  41. }
  42.        
  43. private String getFile(File jar, String requestedFile) throws IOException{
  44.     ByteArrayOutputStream out = new ByteArrayOutputStream(); //change ouptut stream as required
  45.     ZipInputStream in = null;
  46.     try {
  47.         in = new ZipInputStream(new FileInputStream(jar));
  48.         ZipEntry entry;
  49.         while((entry  = in.getNextEntry())!=null){
  50.             if (entry.getName().equals(requestedFile)){
  51.  
  52.                 byte[] buf = new byte[1024];
  53.                 int len;
  54.                 while ((len = in.read(buf)) > 0) {
  55.                     out.write(buf, 0, len);
  56.                 }
  57.             }
  58.         }
  59.     } finally {
  60.         if (in!=null){
  61.             in.close();
  62.         }
  63.         out.close();
  64.  
  65.     }
  66.     return new String(out.toByteArray());
  67. }
  68.        
  69. META-INF/MANIFEST.MF
  70. images/pic.gif
  71. files/abc.txt
  72. files/xxx.txt
  73.        
  74. jar xf yyy.jar files/xxx.txt