Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中读取属性文件_Java_Properties - Fatal编程技术网

在Java中读取属性文件

在Java中读取属性文件,java,properties,Java,Properties,我有以下代码试图读取属性文件: Properties prop = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream stream = loader.getResourceAsStream("myProp.properties"); prop.load(stream); 我在最后一行遇到一个异常。具体而言: Exception

我有以下代码试图读取属性文件:

Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);
我在最后一行遇到一个异常。具体而言:

Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)
谢谢,
Nikos

基于您的异常,
InputStream
为空,这意味着类加载器找不到您的属性文件。我猜myProp.properties位于项目的根目录中,如果是这种情况,则需要前面的斜杠:

InputStream stream = loader.getResourceAsStream("/myProp.properties");

确保文件名正确,并且文件实际位于类路径中<如果不是这种情况导致最后一行抛出异常,则code>getResourceAsStream()将返回null


如果myProp.properties位于项目的根目录中,请改用
/myProp.properties

给定上下文,则应使用
loader.getResourceAsStream(“myPackage/myProp.properties”)

前导的
'/'
不适用于
类加载器.getResourceAsStream(String)
方法

或者,您可以使用
Class.getResourceAsStream(String)
方法,该方法使用
'/'
确定路径是绝对路径还是相对于类位置

示例:


您的文件应该在类路径中以
com/example/foo/myProps.properties
的形式提供。然后将其加载为:

props.load(this.getClass().getResourceAsStream("myProps.properties"));

您可以使用
ResourceBundle
class来读取属性文件

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");

您可以在此页面上找到信息:

你不能像这样使用这个关键字-

props.load(this.getClass().getResourceAsStream("myProps.properties"));
在静态上下文中

最好是掌握应用程序上下文,如——

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/app-context.xml");
然后可以从类路径加载资源文件-

//load a properties file from class path, inside static method
        prop.load(context.getClassLoader().getResourceAsStream("config.properties"));

这将适用于静态和非静态上下文,最好的部分是此属性文件可以位于应用程序类路径中包含的任何包/文件夹中。

您可以使用java.io.InputStream读取文件,如下所示:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(myProps.properties); 

conf/filename.properties
基于项目根目录

如果您的属性文件路径和java类路径相同,那么您应该这样做

例如:

src/myPackage/MyClass.java

src/myPackage/MyFile.properties


要按原始顺序读取属性文件,请执行以下操作:

    File file = new File("../config/edc.properties");
    PropertiesConfiguration config = new PropertiesConfiguration();
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    layout.load(new InputStreamReader(new FileInputStream(file)));

    for(Object propKey : layout.getKeys()){
        PropertiesConfiguration propval =  layout.getConfiguration();
        String value = propval.getProperty((String) propKey).toString();
        out.print("Current Key:" + propkey + "Current Value:" + propval + "<br>");
    }
File File=new文件(“../config/edc.properties”);
PropertiesConfiguration配置=新建PropertiesConfiguration();
PropertiesConfiguration布局=新的PropertiesConfiguration布局(配置);
加载(新的InputStreamReader(新文件InputStream(文件));
对于(对象propKey:layout.getKeys()){
PropertiesConfiguration propval=layout.getConfiguration();
String value=propval.getProperty((String)propKey.toString();
输出。打印(“当前键:+propkey+”当前值:+propval+“
”; }
这里的许多答案描述了一些危险的方法,这些方法实例化了文件输入流,但没有获取输入流的引用,以便稍后关闭该流。这会导致悬空输入流和内存泄漏。加载属性的正确方法应类似于以下内容:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }
String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

注意
try with resources
块中文件输入流的实例化。由于
FileInputStream
是自动关闭的,因此在退出
try with resources
块后,它将自动关闭。如果要使用简单的
try
块,必须使用
fis.close()显式关闭它
finally
块中。

当前的答案中没有一个显示
InputStream
正在关闭(这将泄漏文件描述符),和/或不处理
.getResourceAsStream()
在未找到资源时返回null(这将导致出现
NullPointerException
,并显示令人困惑的消息,
“inStream参数为null”
)。您需要以下内容:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }
String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

指定从src开始的路径,如下所示:

src/main/resources/myprop.proper

如果您的config.properties不在src/main/resource目录中,而在项目的根目录中,则需要执行以下操作:-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

我知道这是一个老问题。如果将来有人偶然发现这一点,我认为这是一个简单的方法。 将属性文件保留在项目文件夹中

        FileReader reader = new FileReader("Config.properties");

        Properties prop = new Properties();
        prop.load(reader);

我的文件层次结构是:src->myPackage->myClass.java,myProp.properties。我按照你的建议做了,但它仍然抛出相同的异常由于你的属性文件不在项目的根目录下,你不需要前导斜杠。我一开始就抛出了没有前导斜杠的异常。它仍然不起作用。我的文件hierarchy是:src->myPackage->myClass.java,myProp.properties。我按照你的建议做了,但是它仍然抛出相同的异常
getResourceAsStream
在类路径上搜索文件。如果你的属性文件在
myPackage
的包目录中,那么使用
/myPackage/myProp.properties
作为路径。@Mark Elliot如果我有一个
conf
包来存储我的所有配置文件,并且我的文件层次结构是:
myproject->src,conf,test
,我如何通过添加前面的斜杠来加载属性?如何在java中将InputStream转换为文件?我想使用文件APIResourceBundle rb=ResourceBundle.ge读取.properties文件t绑定(“myProp”);此方法适用于i18n。ApplicationContext仅在Spring应用程序中可用。不要忘记在
prop.load(Reader)中关闭
读卡器
,根据文档:
指定流在该方法返回后保持打开状态
该链接中有许多方法。为什么选择带有类加载器的方法?该方法有什么优点或缺点?
Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);
        FileReader reader = new FileReader("Config.properties");

        Properties prop = new Properties();
        prop.load(reader);