如题:   假设存在一个jar包,里面的有些文件需要替换。之前都是手工用winara打开不解压,然后把需要改变的文件黏贴进去替换的。如果存在很多图片的话,我希望通过代码实现。   请教如何实现!

解决方案 »

  1.   

    JDK提供了一个JarFile类用来处理Jar文件的,不过只提供了读的功能你可以通过如下步骤实现你的目标:
    1) 通过JarFile读出Jar包信息。
    2) 根据读出的信息将Jar包解压至临时目录。
    3) 在临时目录里替换文件。
    4) 通过RunTime.exex()执行控制台命令重新生成Jar包附一段别人写的解压Jar包代码:
    public static void unzip(ZipFile zipFile, String localPath, int bufferSize) {
    byte[] buffer = new byte[bufferSize];
    ZipInputStream zip = null;
    ZipEntry zipEntry = null;
    try {
    zip = new ZipInputStream(new FileInputStream(zipFile.getName()));
    while ((zipEntry = zip.getNextEntry()) != null) {
    File file = new File(localPath, zipEntry.getName()).getAbsoluteFile();
    System.out.println(file.getName());
    if (zipEntry.isDirectory()) {
    file.mkdirs();
    } else {
    File parent = file.getParentFile();
    if (!parent.exists()) {
    parent.mkdirs();
    }
    file.createNewFile();
    long size = zipEntry.getSize();
    FileOutputStream fos = null;
    try {
    fos = new FileOutputStream(file);
    int readLen = -1;
    while (size != 0) {
    readLen = zip.read(buffer);
    size -= readLen;
    if (readLen != -1) {
    fos.write(buffer, 0, readLen);
    }
    }
    } finally {
    if (fos != null) {
    fos.close();
    }
    }
    }
    }
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (zip != null) {
    zip.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
      

  2.   

    写个bat文件,bat调用jar命令解压,然后调用copy命令把图片拷贝到相应的文件夹,然后再调用jar归档
    在java里用Runtime.getRuntime().exec调用bat
      

  3.   

    使用ant里面的jarEntity工具,去读写jar工具。
      

  4.   

    java提供了zip操作,jar文件实际是使用zip压缩的,看一楼的代码就知道