Java 如何在 WAR 应用程序中读取 MANIFEST.MF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4239368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read MANIFEST.MF inside WAR application?
提问by yegor256
I would like to read MANIFEST.MF
of my WAR
application. How can I find its file name?
我想阅读MANIFEST.MF
我的WAR
申请。我怎样才能找到它的文件名?
采纳答案by BalusC
How can I find its file name?
我怎样才能找到它的文件名?
You already have it. Maybe you meant to find the absolute file location? You can use ServletContext#getRealPath()
for this.
你已经拥有了。也许你想找到绝对文件位置?您可以ServletContext#getRealPath()
为此使用。
String relativeWARPath = "/META-INF/MANIFEST.MF";
String absoluteDiskPath = getServletContext().getRealPath(relativeWARPath);
File file = new File(absoluteDiskPath);
// ...
Or if you want to get it as InputStream
directly, use ServletContext#getResourceAsStream()
.
或者,如果您想InputStream
直接获取它,请使用ServletContext#getResourceAsStream()
.
InputStream input = getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF");
// ...
回答by yegor256
I had the same problem in every application and decided to create a component with a utility class in it: jcabi-manifests. Now it's easy to load any attribute from one of available MANIFEST.MF
in classpath:
我在每个应用程序中都遇到了同样的问题,并决定创建一个包含实用程序类的组件:jcabi-manifests。现在可以很容易地从MANIFEST.MF
类路径中的可用属性之一加载任何属性:
import com.jcabi.manifests.Manifests;
String value = Manifests.read("My-Version");
Also, check this out: http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html
另外,看看这个:http: //www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html
回答by wonhee
There are a few ways to do it, and the chosen answer is only works when you want to read Manifiest files on Servlet/SpringMVC layer or whatever layer you can access to ServletContext.
有几种方法可以做到这一点,所选择的答案仅在您想要读取 Servlet/SpringMVC 层或您可以访问 ServletContext 的任何层上的 Manifyingt 文件时才有效。
However, if you want to read a value like "version" even before Servlet starts up, like during logback configuration or something else, you might need to do some old-way classloading or Manifest file manipulation.
但是,如果您想在 Servlet 启动之前读取“version”之类的值,例如在 logback 配置或其他期间,您可能需要执行一些旧的类加载或 Manifest 文件操作。
I found this github repository(not mine) and it includes 4 different way to read information from Manifest file. If your situation is not accessible to ServletContext, check these out.
我找到了这个 github 存储库(不是我的),它包含 4 种从清单文件中读取信息的不同方式。如果 ServletContext 无法访问您的情况,请查看这些。