1.txt文件如下
2.创建main主类
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("lxj");
MongoCollection<Document> collection = db.getCollection("test");
File file = new File("D:/test/demo.txt");
BufferedReader reader = null;
List<String> head = new ArrayList<>();
head.add("name");
head.add("age");
head.add("address");
List<Document> docs = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
Document document = new Document();
String[] split = tempString.split("\t\t");
int length = split.length;
System.out.println(length);
System.out.println(tempString);
for (int i = 0; i < head.size(); i++) {
document.put(head.get(i), split[i]);
}
docs.add(document);
}
reader.close();
collection.insertMany(docs);
} catch (IOException e) {
e.printStackTrace();
}
}