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

博客轉自:http://blog.csdn.net/liaomin416100569/article/details/6128225/ 


//利用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{
  String path = "E://tomcat//webapps//bdlp//WEB-INF//lib//ant.jar";
  JarFile file = new JarFile(path);

  //這裏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));
   }

  }
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章