读取jar/war文件中的maven.properties文件 [英] Read maven.properties file inside jar/war file

查看:301
本文介绍了读取jar/war文件中的maven.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Java读取jar/war文件中文件(maven.properties)的内容?当不使用文件时(在内存中),我需要从磁盘读取文件.有关如何执行此操作的任何建议?

Is there a way to read the content of a file (maven.properties) inside a jar/war file with Java? I need to read the file from disk, when it's not used (in memory). Any advise on how to do this?

关于, 约翰·基斯(Johan-Kees)

Regards, Johan-Kees

推荐答案

首先要解决的问题:从技术上讲,它不是文件. JAR/WAR是一个文件,您正在寻找的是归档文件中的一个条目(又称为资源).

One thing first: technically, it's not a file. The JAR / WAR is a file, what you are looking for is an entry within an archive (AKA a resource).

由于它不是文件,因此您需要将其作为InputStream

And because it's not a file, you will need to get it as an InputStream

  1. 如果JAR/WAR位于 classpath,您可以执行SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"),其中SomeClass是JAR/WAR中的任何类

  1. If the JAR / WAR is on the classpath, you can do SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"), where SomeClass is any class inside that JAR / WAR

// these are equivalent:
SomeClass.class.getResourceAsStream("/abc/def");
SomeClass.class.getClassLoader().getResourceAsStream("abc/def");
// note the missing slash in the second version

  • 否则,您将必须像这样阅读JAR/WAR:

  • If not, you will have to read the JAR / WAR like this:

    JarFile jarFile = new JarFile(file);
    InputStream inputStream =
        jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
    


  • 现在您可能想将InputStream加载到Properties对象中


    Now you probably want to load the InputStream into a Properties object:

    Properties props = new Properties();
    // or: Properties props = System.getProperties();
    props.load(inputStream);
    


    或者您可以将InputStream读取为字符串.如果您使用类似


    Or you can read the InputStream to a String. This is much easier if you use a library like

    String str = IOUtils.toString(inputStream)
    

  • Google番石榴

    String str = CharStreams.toString(new InputStreamReader(inputStream));
    

  • 这篇关于读取jar/war文件中的maven.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆