我正在尝试使用属性文件来参数化与 Mongodb 的连接。
我添加了这个功能:
public static Properties load(String filename) throws IOException, FileNotFoundException{
  Properties properties = new Properties();
  FileInputStream input = new FileInputStream(filename);
  try{
     properties.load(input);
     return properties;
  }
     finally{
     input.close();
  }
}
并使用此代码:
    String path = System.getProperty("user.dir") + "/config.properties";
    Properties prop = load(path);
    //System.out.println("key: "+ prop.getProperty("MONGO_HOST"));
    try {
//m = new Mongo(config.MONGO_HOST, config.MONGO_PORT);
    m = new Mongo(prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
this.db = m.getDB("cloud_datasource");
             db.authenticate(config.MONGO_USER, config.MONGO_PASS.toCharArray());
    } catch (Exception e) {
System.out.println("Can't connect to MongoDB");
             e.printStackTrace();
    }
在我的 config.properties 中:MONGO_HOST="192.168.10.84"
问题:使用此代码,我有一个错误java.net.UnknownHostException: "192.168.10.84"
,但如果我使用的是代码:
m = new Mongo("192.168.10.84", config.MONGO_PORT);
有用。