[英]Save a reader of a file in a database in Java
我有一個使用Java的閱讀器:閱讀器(Reader read)
來自行數為1'000.000的文件
我需要將每一行保存在數據庫中,我正在閱讀Reader,例如:
int data = read.read();
String line = "";
while (data != -1) {
char dataChar = (char) data;
data = read.read();
if (dataChar != '\n') {
line = line + dataChar;
} else {
i++;
showline(line);
line = "";
}
}
然后我在每一行中調用我的DAO:
private static void showline(String line) {
try {
if (line.startsWith(prefix)) {
line = line.substring(prefix.length());
}
ms = new Msisdn(Long.parseLong(line, 10), idList);
ListDAO.createMsisdn(ms);
} catch (Exception e) {
}
}
我的DAO是:
public static void createMsisdn(Msisdn msisdn) {
EntityManager e = DBManager.createEM();
try {
createMsisdn(msisdn, e);
} finally {
if (e != null) {
e.close();
}
}
}
public static void createMsisdn(Msisdn msisdn, EntityManager em) {
em.getTransaction().begin();
em.persist(msisdn);
em.getTransaction().commit();
}
但是我的問題是,對於包含1'000.000行的文件,大約需要1小時30分鍾才能完成。 我怎樣才能使其更快?
(我的主要問題是調用DAO的時間為1'000.000,因為它非常慢,因為時機較快,沒有調用DAO的時間少於1分鍾,但是調用DAO的時間為2分鍾小時)
讀取字符並將它們一個接一個地追加到String
是非常低效的。 使用BufferedReader
讀取文本行會更好:
String line;
BufferedReader reader = new BufferedReader(read);
while ((line = reader.readLine()) != null) {
showline(line);
}
但是,這對您的情況沒有太大影響:您將每行插入一個單獨的事務中,並且每個事務可能需要數百毫秒才能完成。 您應該以一種可以在單個事務中插入幾行的方式來構造代碼。 例如,您可以讀取這樣的行塊,但必須更改顯示showlines
和createMsisdn
方法,以使它們一次接受多個並分批處理:
final int TRANSACTION_SIZE = 500;
int i = 0;
String[] lines = new String[TRANSACTION_SIZE];
BufferedReader reader = new BufferedReader(read);
while ((lines[i] = reader.readLine()) != null) {
if (i >= lines.length) {
showlines(lines, lines.length);
i = 0;
} else {
i++;
}
}
if (i > 0) showlines(lines, i);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.