0

我正在尝试使用属性文件来参数化与 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);

有用。

4

2 回答 2

0

试试这个(不带引号):

MONGO_HOST=192.168.10.84
于 2011-06-30T15:03:13.133 回答
0

确保 Tomasz 说了什么(道具文件中没有双引号)。然后如果它仍然不起作用,那么可以将 prop.getProperty() 转换为这样的字符串:

m = new Mongo((String)prop.getProperty("MONGO_HOST"), config.MONGO_PORT);
于 2011-06-30T15:07:54.517 回答