如何将属性对象中的数据保存到文件中+如何在另一方法中将属性格式的文件加载到属性对象中? 文字属性阅读属性

问题描述

我想使用以下参数将数据从属性objecet 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加载到Properties对象并返回它:

@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!");

在这里想念什么?

解决方法

以下示例使用java.nio.file软件包,由于其改进的错误处理,应优先于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;
}