1. 程式人生 > >使用java實現讀取txt檔案,匯入到MongoDB中

使用java實現讀取txt檔案,匯入到MongoDB中

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();
        }
    }