在从JAR包中读取指定类的字节码中,使用JarFile读取Jar包,有的XML文件无法被读取到。因此,使用读取Zip的方式读取XML文件。
public int readZipFile(String zipFilePath, String sourcePath, String targetPath) {
try {
int byte_sum = 0;
int byte_read = 0;
byte[] buffer = new byte[1024];
File targetFile = new File(targetPath);
targetFile.createNewFile();
// 文件不存在创建流会失败,因此上一步创建新文件
FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
ZipFile zipFile = new ZipFile(zipFilePath);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (zipEntry.getName().equals(sourcePath)) {
InputStream inputStream = zipFile.getInputStream(zipEntry);
while ((byte_read = inputStream.read(buffer)) != -1) {
byte_sum += byte_read;
fileOutputStream.write(buffer, 0, byte_read);
}
break;
}
}
// 返回被写入目标文件的大小
return byte_sum;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}