zoukankan      html  css  js  c++  java
  • 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{
      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包中某个文件夹的所有文件 这个就不写出了 自己写吧 很简单

  • 相关阅读:
    python使用消息队列RabbitMq(入门)
    python Condition类(锁)
    python锁
    python多线程的几种情形分析-三种情况
    git基本使用
    python学习笔记之数据类型、字符编码、文件处理
    NOIP2018提高组模拟题(五)
    10.28模拟赛
    差分+树状数组【p4868】Preprefix sum
    线段树【p2706】贪婪大陆
  • 原文地址:https://www.cnblogs.com/liaomin416100569/p/9331536.html
Copyright © 2011-2022 走看看