日期:2014-05-20  浏览次数:20953 次

如何替换指定jar中的class文件
void   backupJar(File   fileFrom)   throws   IOException   {

JarEntry   jarEntry;
byte[]   buffer   =   new   byte[1024];
JarInputStream   jarIn;
JarOutputStream   jarOut;
JarFile   jarfile;
Manifest   manifest;

backFile   =   new   File(fileFrom.getParentFile(),   fileFrom.getName()
.replace( ".jar ",   "_v1.jar "));
if   (!backFile.exists())
backFile.createNewFile();
jarfile   =   new   JarFile(fileFrom);
manifest   =   jarfile.getManifest();
jarIn   =   new   JarInputStream(new   FileInputStream(fileFrom));
jarOut   =   new   JarOutputStream(new   FileOutputStream(backFile),   manifest);
while   ((jarEntry   =   jarIn.getNextJarEntry())   !=   null)   {

if   ( "META-INF/MANIFEST.MF ".equals(jarEntry.getName()))
continue;
jarOut.putNextEntry(jarEntry);
int   read;
while   ((read   =   jarIn.read(buffer))   !=   -1)   {
jarOut.write(buffer,   0,   read);
}
jarOut.closeEntry();
}
jarOut.flush();
jarOut.close();
jarIn.close();
}

通过上面的代码,我可以成功复制一个jar文件
   
              但现在的问题是,我需要将原来jar文件中的某几个class更新为现在工程下的source目录中的的class文件,需要如何操作,我是这样考虑的,但是总是异常无法得到正确结果,还望高手能够帮助解决问题!!!



void   updataFile(File   fileFrom)   throws   IOException   {
JarEntry   jarEntry;
byte[]   buffer   =   new   byte[1024];
JarInputStream   jarIn;
JarOutputStream   jarOut;
JarFile   jarfile;
Manifest   manifest;

File   modifyFile   =   new   File(fileFrom.getParentFile(),   fileFrom.getName()
.replace( ".jar ",   "_v2.jar "));
if   (!modifyFile.exists())
modifyFile.createNewFile();
jarfile   =   new   JarFile(fileFrom);
manifest   =   jarfile.getManifest();

jarIn   =   new   JarInputStream(new   FileInputStream(fileFrom));
jarOut   =   new   JarOutputStream(new   FileOutputStream(modifyFile),   manifest);
while   ((jarEntry   =   jarIn.getNextJarEntry())   !=   null)   {
String   jarName   =   jarEntry.getName();

if   ( "META-INF/MANIFEST.MF ".equals(jarName))
continue;

jarOut.putNextEntry(jarEntry);

if   (updateEntry.contains(jarName))   { //如果是需要更新的class的话
String   name   =   "source\\ "
+   jarName.substring(jarName.lastIndexOf( "/ ")   +   1);

DataInputStream   temp   =   new   DataInputStream(new   FileInputStream(name));
int   read;
while   ((read   =   temp.read(buffer))   !=   -1)   {
jarOut.write(buffer,   0,   read);
System.out.println(buffer);
}

}   else   {
int   read;
while   ((read   =   jarIn.read(buffer))   !=   -1)
jarOut.write(buffer,   0,   read);
System.out.println( "---class--2-------->               "
+   jarEntry.getName());
}