栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从代码更新.JAR的内容

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从代码更新.JAR的内容

Java JAR文件是普通的ZIP文件。因此,您可以使用处理ZIP的代码来打开和修改它。

这是一个有效的代码片段(由David提供):

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class JarUpdater {    public static void main(String[] args) {        File[] contents = {new File("F:\ResourceTest.txt"),     new File("F:\ResourceTest2.bmp")};        File jarFile = new File("F:\RepackMe.jar");        try { updateZipFile(jarFile, contents);        } catch (IOException e) { e.printStackTrace();        }    }    public static void updateZipFile(File zipFile,  File[] files) throws IOException {    // get a temp file        File tempFile = File.createTempFile(zipFile.getName(), null);    // delete it, otherwise you cannot rename your existing zip to it.        tempFile.delete();        boolean renameOk=zipFile.renameTo(tempFile);        if (!renameOk)        { throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());        }        byte[] buf = new byte[1024];        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));        ZipEntry entry = zin.getNextEntry();        while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (File f : files) {     if (f.getName().equals(name)) {         notInFiles = false;         break;     } } if (notInFiles) {     // Add ZIP entry to output stream.     out.putNextEntry(new ZipEntry(name));     // Transfer bytes from the ZIP file to the output file     int len;     while ((len = zin.read(buf)) > 0) {         out.write(buf, 0, len);     } } entry = zin.getNextEntry();        }        // Close the streams     zin.close();        // Compress the files        for (int i = 0; i < files.length; i++) { InputStream in = new FileInputStream(files[i]); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) {     out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close();        }        // Complete the ZIP file        out.close();        tempFile.delete();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469803.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号