如何将数据从属性对象保存到文件+如何用另一种方法将属性格式化文件加载到属性对象?

egdjgwm8  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(224)

我想保存属性对象的数据 config 到文件 configFile 在如下参数中:

@Override
public void saveConfig(Properties config, File configFile) {

    try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(configFile));
        os.writeObject(config);
        os.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

在下一个方法中,我要加载格式化的属性 configFile 返回属性对象并返回它:

@Override
public Properties loadConfig(File configFile) {

    Properties prop = new Properties();

    try(InputStream input = new FileInputStream(configFile)){
        prop.load(input);
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return prop;
}

不知何故,junit测试向我展示了一个nullpointerexeption(注意:这是一个考试)

if (!config.getProperty("testKey").equals("testValue"))
        fail("sample config data doesn't match read config data!");

我错过了什么?

chhkpiq4

chhkpiq41#

以下示例使用 java.nio.file 应优先考虑的 Package java.io.File 因为它改进了错误处理。但是,代码将类似地查找 java.io.File 也。

写入属性

@Override
public void saveConfig(Properties config, Path configFile) throws IOException {
    // Comments to be written at the beginning of the file;
    // `null` for no comments
    String comments = ...

    // try-with-resources to close writer as soon as writing finished
    // java.nio.file.Files.newBufferedWriter​(...) uses UTF-8 by default
    try (Writer writer = Files.newBufferedWriter(configFile)) {
        config.store(writer, comments);
    }
}

读取属性

@Override
public Properties loadConfig(Path configFile) throws IOException {
    Properties config = new Properties();

    // try-with-resources to close reader as soon as reading finished
    // java.nio.file.Files.newBufferedReader(...) uses UTF-8 by default
    try (Reader reader = Files.newBufferedReader(configFile)) {
        config.load(reader);
    }

    return config;
}

相关问题