无法从Java读取属性文件

时间:2018-07-15 12:52:52

标签: java eclipse selenium properties-file

我无法从文件中读取属性。当我尝试打印时,它为我提供了空值;当我调试时,我知道它没有在函数中加载文件 pro.Load()。但是我的路径是正确的,但仍然无法加载文件

package AdvancedJava;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class ReadingPropertiesFile {

public static void main(String[] args) throws FileNotFoundException {
    Properties pro = new Properties();

    String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";

    // BufferedReader reader = new BufferedReader(new FileReader(path));
    File f = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        pro.load(fis);
    }

    catch (IOException e) {
        System.out.println(e.getMessage());
    }

    System.out.println(pro.getProperty("lastname"));

  }

}

属性文件内容

firstname = John
lastname = harry
Automation = Selenium

3 个答案:

答案 0 :(得分:2)

我认为问题出在路径上

String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";

应该是这样的:

String path = "C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";

还要确保您具有正确的属性文件路径。如果它在您的项目中,则路径应如下所示:

String path = "C:\\...\\ProjectFolder\\src\\main\\resources\\object.properties";

答案 1 :(得分:1)

您的示例对我来说很好。但是,如果没有堆栈跟踪,我们将无法帮助您解决正在获得的NPE。

尽管如此,我还是有一些关于您的代码的提示。我建议在使用FileInputStream时使用try-资源,以确保一旦完成将关闭资源。

您可以避免使用new File(path);。相反,我建议使用Paths包中的java.nio.*。基于您的代码段的示例如下:

public static void main(String[] args) {
    Properties properties = new Properties();
    try (FileInputStream stream = new FileInputStream(Paths.get("E:\\test\\file.txt").toFile())) {
        properties.load(stream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(properties.getProperty("lastname"));
}

使用Paths的优势在于,它们是系统不可知的(如果没有记错的话),您不必担心提供正确的路径定界符。

答案 2 :(得分:1)

实际上,路径应该使用另一个分隔符

"C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";

但是我建议您-将您的应用属性文件存储在资源文件夹下,有点:

src/main/resources/config.properties

比您将能够像这样访问此文件:

public Properties extractFrom(String fileName) {
    Properties properties = new Properties();

    try (InputStream inputStream = PropertiesExtractor.class
            .getClassLoader().getResourceAsStream(fileName)) {
        properties.load(inputStream);
    } catch (IOException ex) {
        throw new RuntimeException("Cannot load properties", ex);
    }

    return properties;
}

extractFrom("config.properties");
相关问题