What is the proper way to parse the entries of a m

2020-03-11 03:05发布

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条回答
何必那么认真
2楼-- · 2020-03-11 03:12

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
查看更多
登录 后发表回答