java修改jar包文件内容的一个实例 (二)

2014-11-24 07:39:58 · 作者: · 浏览: 8
_MOVE, new MyDropTargetListener(this));
this.setTitle("CfgViewer0.1");
this.setVisible(true);
}

/**
* 写入jar文件的话会将 jar文件原来的内容统统抹掉!!切记!!~
*/
private void write2JarFile() {
String originalPath = original.getAbsolutePath();
/** 创建一个临时文件来做暂存,待一切操作完毕之后会将该文件重命名为原文件的名称(原文件会被删除掉)~ */
String tempPath = originalPath.substring(0, originalPath.length()-4) + "_temp.jar";
System.out.println(tempPath);

JarFile originalJar = null;
try {
originalJar = new JarFile(originalPath);
} catch (IOException e1) {
e1.printStackTrace();
}
List lists = new LinkedList();
for(Enumeration entrys = originalJar.entries(); entrys.hasMoreElements();) {
JarEntry jarEntry = entrys.nextElement();
// System.out.println(jarEntry.getName());
lists.add(jarEntry);
}

// 定义一个 jaroutputstream 流
File handled = new File(tempPath);
JarOutputStream jos = null;
try {
FileOutputStream fos = new FileOutputStream(handled);
jos = new JarOutputStream(fos);

/**
* 将源文件中的内容复制过来~
* 可以利用循环将一个文件夹中的文件都写入jar包中 其实很简单
*/
for(JarEntry je : lists) {
// jar 中的每一个文件夹 每一个文件 都是一个 jarEntry
JarEntry newEntry = new JarEntry(je.getName());

// newEntry.setComment(je.getComment());
// newEntry.setCompressedSize(je.getCompressedSize());
// newEntry.setCrc(je.getCrc());
// newEntry.setExtra(je.getExtra());
// newEntry.setMethod(je.getMethod());
// newEntry.setTime(je.getTime());
// System.out.println(je.getAttributes());
/** 这句代码有问题,会导致将jar包重命名为zip包之后无法解压缩~ */
// newEntry.setSize(je.getSize());

// 表示将该entry写入jar文件中 也就是创建该文件夹和文件
jos.putNextEntry(newEntry);

/** 如果当前已经处理到属性文件了,那么将在 JTextArea 中编辑过的文本写入到该属性文件~ */
if(je.getName().equals(configPath)) {
jos.write(jta.getText().getBytes());
continue;
}

InputStream is = originalJar.getInputStream(je);
byte[] bytes = inputStream2byteArray(is);
is.close();

// 然后就是往entry中的jj.txt文件中写入内容
jos.write(bytes);
}
// 最后不能忘记关闭流
jos.close();
fos.close();

/** 删除原始文件,将新生成的文件重命名为原始文件的名称~ */
original.delete();
handled.renameTo(new File(originalPath));
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* InputStream 转 byte[]~
* @param is
* @return
*/
public static byte[] inputStream2byteArray(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
try {
while((i = is.read()) != -1) {
baos.wr