我正在构建MongoDB的Java API。更具体地说,现在我正在尝试封装连接到MongoDB的过程,并在单个方法中从该数据库中选择一个数据库和一个集合到它自己的类。
package mongoDB;
import java.net.UnknownHostException;
import java.util.*;
import com.mongodb.*;
public class MongoDBConnector {
public DBCollection mongoEasy (String hostname, int port) {
try {
Mongo m = new Mongo(hostname, port);
//choose database
List<String> databaseNames = m.getDatabaseNames();
System.out.println("Choose database: " + databaseNames.toString());
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(!databaseNames.contains(input.toString())){
System.out.println("Database does not exist.");
System.exit(1);
}
DB db = m.getDB(input.toString());
//choose collection
Set<String> collectionNames = db.getCollectionNames();
System.out.println("Choose collection " + collectionNames.toString());
input = scanner.nextLine();
if(!collectionNames.contains(input.toString())){
System.out.println("collection does not exist");
System.exit(1);
}
DBCollection dbCollection = db.getCollection(input.toString());
scanner.close();
return dbCollection;
} catch (UnknownHostException e) {
System.out.println("Connection failed.");
System.exit(1);
} catch(MongoException e){
System.out.println("Fail.");
System.exit(1);
} finally{
}
return null;
}
}
如果我创建一个MongoDBConnector实例并在main方法中一次调用mongoEasy一切都很好。但是,如果我第二次调用该方法,它会泵出NoSuchElementException。举个例子: 包mongoDB;
import com.mongodb.*;
import mongoDB.MongoDBConnector;
public class MongoDBOperations2 {
public static void main(String[] args) {
MongoDBConnector mongoDBConnector = new MongoDBConnector();
DBCollection collection = mongoDBConnector.mongoEasy("localhost", 27017);
collection = mongoDBConnector.mongoEasy("localhost", 27017);
}
}
每当我试图执行此操作时,我得到(我删除了数据库,主要方法的集合名称和行号不适合,因为我简化了问题):
Choose database [...]
test
Choose collection [...]
test
Choose database [local, StudiumUlm, test]
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at mongoDB.MongoDBConnector.mongoEasy(MongoDBConnector.java:18)
at mongoDB.MongoDBOperations2.main(MongoDBOperations2.java:)
第二次调用方法时,扫描仪没有等待输入。有什么建议吗?
感谢。 干杯, 马格努斯
答案 0 :(得分:0)
根据Scanner.close()文档,如果它实现了 Closeable ,它将关闭底层的Reader / Stream。
由于您的代码关闭了扫描程序,因此您无法在第一次之后从System.in读取(这正是您所看到的)。
为什么不向 MongoDBConnector 添加close方法,如:
public class MongoDBConnector {
Scanner scanner;
public MongoDBConnector() {
this.scanner = new Scanner(System.in);
}
public void close(){
this.scanner.close();
}
// the rest of your code but don't create a new scanner or close it
}
然后在你的主线上做:
public class MongoDBOperations2 {
public static void main(String[] args) {
MongoDBConnector mongoDBConnector = new MongoDBConnector();
try {
DBCollection collection = mongoDBConnector.mongoEasy("localhost", 27017);
collection = mongoDBConnector.mongoEasy("localhost", 27017);
}finally {
mongoDBConnector.close();
}
}
}