正确使用Apache Commons配置

我的代码如下:

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; 它说The type org.apache.commons.lang.exception.NestableException cannot be resolved. It is indirectly referenced from required .class files The type org.apache.commons.lang.exception.NestableException cannot be resolved. It is indirectly referenced from required .class files
  2. 对于行} catch (ConfigurationException e) {它表示No exception of type ConfigurationException can be thrown; an exception type must be a subclass of Throwable No exception of type ConfigurationException can be thrown; an exception type must be a subclass of Throwable

我在Java中发现了ConfigurationException? ,但提供的解决方案没有帮助。

Apache Commons Configuration的核心具有以下运行时依赖性 :

  • Apache Commons Lang (版本2.2,2.3,2.4,2.5或2.6)
  • Apache Commons Collections (版本3.1,3.2或3.2.1)
  • Apache Commons Logging (版本1.0.4,1.1或1.1.1)

也可以将它们放在类路径中。 您的特定问题是由缺少Lang依赖性引起的。

这个库问题困扰了我几天,直到我弄清楚为什么Apache希望我使用旧库。

如果要求编译器使用旧的Lang库,请确保以新方式创建Apache属性文件,而不是旧方式(使用较旧的lang库)。 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 builder; public Settings(String propertiesFilePath) { Parameters params = new Parameters(); File propFile = new File(propertiesFilePath); builder = new FileBasedConfigurationBuilder(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