现在的位置: 首页 > 综合 > 正文

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

2014年01月24日 ⁄ 综合 ⁄ 共 1646字 ⁄ 字号 评论关闭

 //利用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));
   }

  }
 }

 

当然还有其他的操作 比如读取jar包中某个文件夹的所有文件 这个就不写出了 自己写吧 很简单

抱歉!评论已关闭.