Tôi đã đọc tệp và tạo một đối tượng từ nó và lưu trữ vào cơ sở dữ liệu postgresql. Tệp của tôi có 100.000 tài liệu mà tôi đọc từ một tệp và chia nhỏ tệp đó và cuối cùng lưu trữ vào cơ sở dữ liệu. Tôi không thể tạo List<>
và lưu trữ tất cả tài liệu trong List<>
vì RAM của tôi ít. Mã của tôi để đọc và ghi vào cơ sở dữ liệu như sau. Nhưng My JVM Heap đầy và không thể tiếp tục lưu trữ thêm tài liệu. Cách đọc tệp và lưu trữ cơ sở dữ liệu hiệu quả.Cách chèn dữ liệu càng nhanh càng tốt với Hibernate
public void readFile() {
StringBuilder wholeDocument = new StringBuilder();
try {
bufferedReader = new BufferedReader(new FileReader(files));
String line;
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("<page>")) {
wholeDocument.append(line);
while ((line = bufferedReader.readLine()) != null) {
wholeDocument = wholeDocument.append("\n" + line);
if (line.contains("</page>")) {
System.out.println(count++);
addBodyToDatabase(wholeDocument.toString());
wholeDocument.setLength(0);
break;
}
}
}
}
wikiParser.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addBodyToDatabase(String wholeContent) {
Page page = new Page(new Timestamp(System.currentTimeMillis()),
wholeContent);
database.addPageToDatabase(page);
}
public static int counter = 1;
public void addPageToDatabase(Page page) {
session.save(page);
if (counter % 3000 == 0) {
commit();
}
counter++;
}
Có lẽ bạn cần thêm 'StringBuilder wholeDocument = StringBuilder mới(); 'đâu đó bên trong vòng lặp của bạn –
bằng cách này, StringBuilder được có thể thay đổi, bạn không cần phải làm điều này' wholeDocument = wholeDocument.append (" \ n "+ dòng);', chỉ sử dụng 'wholeDocument.append (" \ n "+ dòng);' –
'commit()' làm gì? –