What is the proper way to parse the entries of a manifest.mf file in jar?

烂漫一生 提交于 2019-12-19 05:22:11

问题


The manifest.mf contained in many Java jars contains headers which look much like email headers. See example [*]

I want something that can parse this format into key value pairs:

Map<String, String> manifest = <mystery-parse-function>(new File("manifest.mf"));

I have googled around a bit for "parse manifest.mf" "manifest.mf format" etc. and I find plenty of information about the meaning of the headers (e.g. in OSGI bundles, standard Java jars, etc.) but that's not what I'm looking for.

Looking at some example manifest.mf files I could probably implement something to parse it (reverse engineer the format) but I won't know if my implementation is actually correct. So I'm also not looking for someone else's quickly thrown together parse function as it suffers the same problem).

A good answer to my question could point me to a specification of the format (so I can write my own correct parse function). The best answer points me to an existing open-source library that already has a correct implementation.

[*] = https://gist.github.com/kdvolder/6625725


回答1:


MANIFEST.MF files can be read with the Manifest class:

Manifest manifest = new Manifest(new FileInputStream(new File("MANIFEST.MF")));

Then you can get all entries by doing

Map<String, Attributes> entries = manifest.getEntries();

And all main attributes by doing

Attributes attr = manifest.getMainAttributes();

A working example

My MANIFEST.MF file is this:

Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

My code:

Manifest manifest = new Manifest(new FileInputStream(new File("MANIFEST.MF")));
Attributes attr = manifest.getMainAttributes();

System.out.println(attr.getValue("Manifest-Version"));
System.out.println(attr.getValue("X-COMMENT"));

Output:

1.0
Main-Class will be added automatically by build


来源:https://stackoverflow.com/questions/18899123/what-is-the-proper-way-to-parse-the-entries-of-a-manifest-mf-file-in-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!