天天看點

java操作生成jar包 和寫入jar包

 //利用jarInputStream生成jar檔案寫入内容

 public static void writeJar()throws Exception{

//定義一個jaroutputstream流

  JarOutputStream stream=new JarOutputStream(new FileOutputStream("E://tomcat//webapps//bdlp//WEB-INF//lib//ant1.jar"));

//jar中的每一個檔案夾 每一個檔案 都是一個jarEntry

//如下表示在jar檔案中建立一個檔案夾bang bang下建立一個檔案jj.txt

  JarEntry entry=new JarEntry("bang/jj.txt");

//表示将該entry寫入jar檔案中 也就是建立該檔案夾和檔案

  stream.putNextEntry(entry);

//然後就是往entry中的jj.txt檔案中寫入内容

  stream.write("我日你".getBytes("utf-8"));

//建立另一個entry1 同上操作 可以利用循環将一個檔案夾中的檔案都寫入jar包中 其實很簡單

  JarEntry entry1=new JarEntry("bang/bb.xml");

  stream.putNextEntry(entry1);

  stream.write("<xml>abc</xml>".getBytes("utf-8"));

//最後不能忘記關閉流

  stream.close();

 }

//要讀取jar包中某一個已知路徑的檔案内容

//像上面一樣 name 相當于路徑 比如 bang/bb.xml

public static String getContent(String name) throws Exception{

  String path = "E://tomcat//webapps//bdlp//WEB-INF//lib//ant.jar";

  JarFile file = new JarFile(path);

  ZipEntry entry= file.getEntry(name);

 //擷取到inputstream了 就相當簡單了

  InputStream stream=file.getInputStream(entry);

  byte[] bb = new byte[stream.available()];

  stream.read(bb);

  return new String(bb);

//讀取jar包中的所有檔案

 public static void readAll() throws Exception{

  //這裡entry的集合中既包括檔案夾 又包括檔案 是以需要到下面做判斷 如e.isDirectory()

  Enumeration<JarEntry> entry = file.entries();

  while (entry.hasMoreElements()) {

   JarEntry e = entry.nextElement();

   if (!e.isDirectory() && !e.getName().endsWith(".class") && !e.getName().endsWith(".gif")) {

    InputStream stream = file.getInputStream(e);

    byte[] bb = new byte[stream.available()];

    stream.read(bb);

    System.out.println(new String(bb));

   }

  }

當然還有其他的操作 比如讀取jar包中某個檔案夾的所有檔案 這個就不寫出了 自己寫吧 很簡單