我正在尝试为OSGi包实现一些“无线”更新机制。为此,我需要能够从String创建一个jar文件(基本上是JarInputStream读取的jar文件的内容)。以下示例代码应说明我的需求:
//read bundle to be copied!
File originalFile = new File(
"/Users/stefan/Documents/Projects/OSGi/SimpleBundle_1.0.0.201404.jar");
JarInputStream fis = new JarInputStream(new FileInputStream(originalFile));
StringBuilder stringBuilder = new StringBuilder();
int ch;
while ((ch = fis.read()) != -1) {
stringBuilder.append((char) ch);
}
fis.close();
//Create content string
String content = stringBuilder.toString();
if (logger.isInfoEnabled()) {
logger.info(content);
}
//Init new jar input stream
JarInputStream jarInputStream = new JarInputStream(
new ByteArrayInputStream(content.getBytes()));
if (logger.isInfoEnabled()) {
logger.info("Save content to disc!");
}
File newFile = new File(
"/Users/stefan/Documents/Projects/OSGi/equinox/SimpleBundle_1.0.0.201404.jar");
//Init new jar output stream
JarOutputStream fos = new JarOutputStream(
new FileOutputStream(newFile));
if (!newFile.exists()) {
newFile.createNewFile();
}
int BUFFER_SIZE = 10240;
byte buffer[] = new byte[BUFFER_SIZE];
while (true) {
int nRead = jarInputStream.read(buffer, 0,
buffer.length);
if (nRead <= 0)
break;
fos.write(buffer, 0, nRead);
}
//Write content to new jar file.
fos.flush();
fos.close();
jarInputStream.close();
不幸的是,如果我尝试使用JD-GUI打开它,则创建的jar文件为空并抛出“无效输入文件”错误。是否可以从字符串“content”创建一个jar文件?
致以最诚挚的问候,非常感谢 斯蒂芬
答案 0 :(得分:1)
你的jar是空的,因为你没有从JarInputStream中读取任何内容。如果要读取JarInputStream,则应迭代其条目。如果要更改Manifest,应跳过第一个条目,使用jarInputStream的getManifest()和JarOutputStream的构造函数,可以指定Manifest。根据您的代码(没有清单更改,但是普通的jar副本):
ZipEntry zipEntry = jarInputStream.getNextEntry();
while (zipEntry != null) {
fos.putNextEntry(zipEntry);
// Simple stream copy comes here
int BUFFER_SIZE = 10240;
byte buffer[] = new byte[BUFFER_SIZE];
int l = jarInputStream.read(buffer);
while(l >= 0) {
fos.write(buffer, 0, l);
l = jarInputStream.read(buffer);
}
zipEntry = jarInputStream.getNextEntry();
}
如果要在复制期间更改JAR文件的内容(Manifest或条目),则只需要此选项。否则,简单的InputStream和FileOutputStream将完成工作(如Tim所说)。