红色部分,将文件转存储,然后重新写入jar文件中。
如果不将原有文件转存储会将原有jar清空
<span style="color:#454545;">package com.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
public class Main2 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception{
// 这里的com.test.Main2.class 一定要写上包名.
String currentJarPath = URLDecoder.decode(com.test.Main2.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码
System.out.println(currentJarPath);
JarFile currentJar = new JarFile(currentJarPath);
JarEntry dbEntry = currentJar.getJarEntry("com/test/text.txt");//这里写上配置文件所在的包路径
InputStream in = currentJar.getInputStream(dbEntry);
BufferedReader reader =new BufferedReader(new InputStreamReader(in));
System.out.println(reader.readLine());
//以上YourClassName是class全名,也就是包括包名
reader.close();
in.close();
currentJar.close(); //读完之后一定要close 不然的话写入的时候会报错.
//写文件
</span><span style="color:#cc0000;">Hashtable <String,byte[]> table = new Hashtable <String,byte[]>();
BufferedInputStream bIn = null;
try{
currentJar=new JarFile(currentJarPath);
Enumeration <JarEntry> entries = currentJar.entries();
/* 第一步:将除了你想修改的其它的entry都保存到table中 */
while(entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
if(entry.getName().indexOf(".") > -1)
{
System.out.println(entry.getName());
if(!entry.getName().equals("com/test/text.txt"))
{
bIn = new BufferedInputStream(currentJar.getInputStream(entry));
int len = bIn.available();
byte[] bt = new byte[len];
bIn.read(bt);
bIn.close();
table.put(entry.getName(), bt);
}
}
}
currentJar.close();
}catch(Exception e)
{
e.printStackTrace();
}
try{
JarEntry entry =new JarEntry("com/test/text.txt");
JarOutputStream out = new JarOutputStream(new FileOutputStream(currentJarPath));
/* 第二步:将你想修改的entry先写到流中 */
out.putNextEntry(entry);
out.write(new Date().toLocaleString().getBytes());
out.flush();
/* 第三步:将保存在table中的其它entry写到流中 */
Enumeration <String> names = table.keys();
while(names.hasMoreElements())
{
String entryName = names.nextElement();
entry = new JarEntry(entryName);
out.putNextEntry(entry);
out.write(table.get(entryName));
out.flush();
}
out.close();
currentJar.close();
}catch(Exception e)
{
e.printStackTrace();
} </span><span style="color:#454545;">
}}</span>
转载自: http://hi.baidu.com/songhaoying/item/adfad02fdc112085af48f52d