Apache Commons Configuration的正确使用方法

17

我的代码如下:

package org.minuteware.jgun;

import org.apache.commons.configuration.*;

class ConfigReader {
    public void getconfig() {
        Configuration config;
        try {
            config = new PropertiesConfiguration("gun.conf");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        String day = config.getString("sync_overlays");
        System.out.println(day);
    }
}

Eclipse在这段代码中有两个问题:

  1. 对于package org.minuteware.jgun;这行代码,它显示无法解析类型org.apache.commons.lang.exception.NestableException。它是从所需的.class文件间接引用的
  2. 对于} catch (ConfigurationException e) {这行代码,它显示不能抛出类型为ConfigurationException的异常;异常类型必须是Throwable的子类

我在Java中遇到了ConfigurationException?找到了相关答案,但提供的解决方案并没有帮助。

2个回答

38

8
问题在于我有Lang3,但需要使用旧版本的Lang2。很奇怪它不支持第三版。 - Andrii Yurchuk
好的,我会编辑答案并包含依赖页面中提到的版本号。 - BalusC
@Andriy Yurchuk - Apache有一种新的方法来处理Lang3的属性文件。请看下面我的“答案”。我知道这已经过去几年了,但希望对那些遇到同样问题的人有所帮助。 - joshpt

1
这个库的问题困扰了我几天,直到我弄清楚为什么Apache要我使用旧的库。
如果编译器要求您使用较旧的Lang库,请确保以新方式而不是旧方式(使用较旧的lang库)创建Apache属性文件。 https://commons.apache.org/proper/commons-configuration/userguide/howto_filebased.html 是我从Apache网站获取的,以下代码对我的Windows机器上的一个文件执行基本的SET操作。
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.FileBasedConfiguration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;

public final class Settings implements Serializable {

private Configuration config;
private String propertiesFilePath;
private FileBasedConfigurationBuilder<FileBasedConfiguration> builder;

public Settings(String propertiesFilePath) {
    Parameters params = new Parameters();
    File propFile = new File(propertiesFilePath);
    builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
            .configure(params.fileBased()
                    .setFile(propFile));
    try {
        config = builder.getConfiguration();
    } catch (Exception e) {
        System.out.println("Exception - Settings constructor: " + e.toString());
    }
}//end constructor

public void setValue(String key, String value) throws Exception {
        config.setProperty(key, value);
        builder.save();
 }// end setter method
}//end class

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接