根据链接:https://stackoverflow.com/a/1281295/1794012
我按照说明创建了一个jar文件,输入目录中创建jar的源文件如下,
当我遍历JarFile#entries方法时,它正在打印以下内容,
当通过JarOutputStream 创建jar时输出META-INF / MANIFEST.MF
d:/所以/
D:/so/some.txt
但我使用jar工具
创建了jar文件jar -cvf so_commond.jar so so / some.txt
添加了清单
添加:so /(in = 0)(out = 0)(存储0%)
添加:so / some.txt(in = 7)(out = 9)(缩小-28%)
现在我使用JarFile#条目来迭代条目,以下是输出
当罐子工具创建jar时输出META-INF / (当JarOutputStream创建jar时,这不存在)
META-INF / MANIFEST.MF
所以/
因此/ some.txt
你能否解释一下为什么jar条目META-INF仅在jar工具创建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();
}
}