0

我有一个 Java 阅读器:阅读器(Reader read)来自一个包含 1'000.000 行的文件

我需要将每一行保存在我的数据库中,我正在阅读阅读器,例如:

            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 次,因为它非常慢,因为 while 更快,没有调用 DAO 的时间不到 1 分钟,但调用 DAO 的时间是 2小时)

4

1 回答 1

0

读取字符并将它们String逐个附加到一个非常低的效率。使用 aBufferedReader阅读文本行要好得多:

        String line;
        BufferedReader reader = new BufferedReader(read);
        while ((line = reader.readLine()) != null) {
            showline(line);
        }

不过,这对您的情况不会有太大影响:您将每一行插入一个单独的事务中,并且每个事务可能需要数百毫秒才能完成。您应该以可以在单个事务中插入多行的方式构建代码。例如,您可以像这样读取行块,但是您必须更改showlinesandcreateMsisdn方法,以便它们一次接受多个并在一个批次中处理它们:

        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);
于 2013-10-07T23:09:30.190 回答