【问题标题】:Extracting a jar from the currently running jar从当前运行的 jar 中提取一个 jar
【发布时间】:2012-05-07 19:27:49
【问题描述】:

我正在尝试从当前运行的 jar 中提取 2 个 jar 文件,但是即使它们的大小分别为 104kb 和 1.7m,它们总是以 2kb 结束,这就是我所拥有的

public static boolean extractFromJar(String fileName, String dest) {
    if (Configuration.getRunningJarPath() == null) {
        return false;
    }
    File file = new File(dest + fileName);
    if (file.exists()) {
        return false;
    }

    if (file.isDirectory()) {
        file.mkdir();
        return false;
    }
    try {
        JarFile jar = new JarFile(Configuration.getRunningJarPath());
        Enumeration<JarEntry> e = jar.entries();
        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            InputStream in = new BufferedInputStream(jar.getInputStream(je));
            OutputStream out = new BufferedOutputStream(
                    new FileOutputStream(file));
            copyInputStream(in, out);
        }
        return true;
    } catch (Exception e) {
        Methods.debug(e);
        return false;
    }
}

private final static void copyInputStream(InputStream in, OutputStream out)
        throws IOException {
    while (in.available() > 0) {
        out.write(in.read());
    }
    out.flush();
    out.close();
    in.close();
}

【问题讨论】:

    标签: java jar extract


    【解决方案1】:

    这应该比依赖 InputStream.available() 方法更好:

    private final static void copyInputStream(InputStream in, OutputStream out)
            throws IOException {
        byte[] buff = new byte[4096];
        int n;
        while ((n = in.read(buff)) > 0) {
            out.write(buff, 0, n);
        }
        out.flush();
        out.close();
        in.close();
    }
    

    【讨论】:

      【解决方案2】:

      available() 方法读取数据不可靠,因为它只是一个估计值,根据其文档。
      您需要依赖 read() 方法,直到读取非 -ve。

      byte[] contentBytes = new byte[ 4096 ];  
      int bytesRead = -1;
      while ( ( bytesRead = inputStream.read( contentBytes ) ) > 0 )   
      {   
          out.write( contentBytes, 0, bytesRead );  
      } // while available
      

      您可以在here 讨论available() 的问题。

      【讨论】:

        【解决方案3】:

        我不确定解压jar,但是每个jar实际上都是一个zip文件,所以你可以尝试解压。

        您可以在此处找到有关在 java 中解压缩的信息: How to unzip files recursively in Java?

        【讨论】:

          猜你喜欢
          • 2012-07-13
          • 1970-01-01
          • 1970-01-01
          • 2014-07-12
          • 2013-07-18
          • 2012-08-23
          • 2014-10-03
          • 2019-09-20
          • 2010-09-10
          相关资源
          最近更新 更多