Java 操作Jar包,删除Jar包内的文件

JDK提供了一套操作Jar包的方法,使用方法如下:


1、JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarName));

2、jos.putNextEntry(entry);

3、jos.write(bytes, 0, bytes.length);


其中,第二步使用的entry可以通过如下方式构造

Enumeration entries = jarFile.entries();

第三步的bytes可以通过如下方式构造

InputStream inputStream = bakJarFile.getInputStream(entry);


整个例子如下:

private static void delete(String jarName, List deletes) throws Exception {
    //先备份
    File oriFile = new File(jarName);
    if (!oriFile.exists()) {
        System.out.println("######Not Find File:" + jarName);
        return;
    }
    //将文件名命名成备份文件
    String bakJarName = jarName.substring(0, jarName.length() - 3) + getTime() + ".jar";
    File bakFile = new File(bakJarName);
    boolean isOK = oriFile.renameTo(bakFile);
    if (!isOK) {
        System.out.println("######Remame ERR..........");
        return;
    }


    //创建文件(根据备份文件并删除部分)
    JarFile bakJarFile = new JarFile(bakJarName);
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarName));
    Enumeration entries = bakJarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (!deletes.contains(entry.getName())) {
            InputStream inputStream = bakJarFile.getInputStream(entry);
            jos.putNextEntry(entry);
            byte[] bytes = readStream(inputStream);
            jos.write(bytes, 0, bytes.length);
        }
        else {
            System.out.println("Delete:-------" + entry.getName());
        }
    }

    jos.flush();
    jos.finish();
    jos.close();
    bakJarFile.close();

}
private static byte[] readStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = -1;
    while ((len = inStream.read(buffer)) != -1) {
        outSteam.write(buffer, 0, len);
    }
    outSteam.close();
    inStream.close();
    return outSteam.toByteArray();
}





你可能感兴趣的:(后端,Java基本语法)