我正在构建 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);
}
}
每当我尝试执行此操作时,我都会得到(我删除了数据库和集合名称以及 main 方法的行号不适合,因为我为问题简化了它):
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:)
我第二次调用该方法时,扫描仪不会等待我的输入。有什么建议么?
谢谢。干杯,马格纳斯