【发布时间】:2017-02-09 12:10:25
【问题描述】:
根据链接:https://stackoverflow.com/a/1281295/1794012
我按照说明创建了一个jar文件,创建jar的源文件的输入目录如下,
- 所以(目录)
- so/some.txt(文件)
当我遍历 JarFile#entries 方法时,它会打印以下内容,
通过 JarOutputStream 创建 jar 时的 JarFile#entries 输出
META-INF/MANIFEST.MF
D:/so/
D:/so/some.txt
但是我使用 jar 工具创建了 jar 文件
使用简单的jar工具创建jar
jar -cvf so_commond.jar so so/some.txt
添加清单
添加:so/(in = 0) (out= 0)(stored 0 %)
添加:so/some.txt(in = 7) (out= 9)(deflated -28%)
现在我使用 JarFile#entries 来迭代条目,以下是输出
jar工具创建jar时的JarFile#entries输出
META-INF/(JarOutputStream 创建 jar 时不存在)
META-INF/MANIFEST.MF
所以/
所以/some.txt
能否请您解释一下为什么jar条目META-INF仅在jar工具创建时显示,而jar在JarOutputStream创建时不显示?
代码:
public static void main(String[] args){
run();
for(Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements();){
System.out.println(e.nextElement().getName());
}
}
public static void run() throws IOException
{
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(new FileOutputStream("D:\\so.jar"),
manifest);
add(new File("D:\\so"), target);
target.close();
}
private static void add(File source, JarOutputStream target) throws IOException
{
BufferedInputStream in = null;
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles())
add(nestedFile, target);
return;
}
JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true)
{
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
}
finally
{
if (in != null)
in.close();
}
}
【问题讨论】: