问题跑一遍就知道,求高手解答!
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
public class Test {
public static void main(String[] args) {
String file = "com.ibm.icu_3.4.5.jar";
String entryName = "about.html";
System.err.println("修改前的" + entryName + ":");
readJar(file, entryName);
byte[] data = new byte[128];
System.err.println("请输入新内容:");
try {
System.in.read(data);
} catch (IOException e) {
e.printStackTrace();
}
editJar(file, entryName, data);
System.err.println("修改后的" + entryName + ":");
readJar(file, entryName);
}
// 读取jar中某一文件
public static void readJar(String file, String entryName) {
try {
JarFile jf = new JarFile(file);
ZipEntry ze = jf.getEntry(entryName);
InputStream is = jf.getInputStream(ze);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while (null != br.readLine()) {
System.out.println(br.readLine());
}
br.close();
isr.close();
is.close();
jf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 修改jar中某一文件
public static void editJar(String file, String entryName, byte[] data) {
try {
JarFile jf = new JarFile(file);
TreeMap tm = new TreeMap();
Enumeration es = jf.entries();
while (es.hasMoreElements()) {
JarEntry je = (JarEntry) es.nextElement();
byte[] b = getByte(jf.getInputStream(je));
tm.put(je.getName(), b);
}
JarOutputStream out = new JarOutputStream(
new FileOutputStream(file));
Set set = tm.entrySet();
Iterator it = set.iterator();
boolean has = false;
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
String name = (String) me.getKey();
JarEntry jeNew = new JarEntry(name);
out.putNextEntry(jeNew);
byte[] b;
if (name.equals(entryName)) {
b = data;
has = true;
} else
b = (byte[]) me.getValue();
out.write(b, 0, b.length);
}
if (!has) {
JarEntry jeNew = new JarEntry(entryName);
out.putNextEntry(jeNew);
out.write(data, 0, data.length);
}
out.finish();
out.close();
jf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 从输入流中取字节
public static byte[] getByte(java.io.InputStream s) {
byte[] buffer = new byte[0];
byte[] chunk = new byte[4096];
int count;
try {
while ((count = s.read(chunk)) >= 0) {
byte[] t = new byte[buffer.length + count];
System.arraycopy(buffer, 0, t, 0, buffer.length);
System.arraycopy(chunk, 0, t, buffer.length, count);
buffer = t;
}
s.close();
} catch (Exception e) {
}
return buffer;
}
}