用NIO写一个大文本文件

时间:2013-12-10 10:14:46

标签: java io nio filechannel

我在我的应用程序中为离线报告编写了一个大的,大约1200(+/- 200)mb的csv文件。 (一个线程执行此作业。)数据计数可能大约为5000万,因此每50k行运行一次查询。查询循环运行直到空取指(对于给定的条件)。要将数据写入文件,而不是使用Java流,我尝试了nio。我花了大约12秒写了一个50000行的巨大字符串。尝试使用BufferedWriter的代码大约需要18-22秒。 nio方法代码如下。我想知道这是否是在编写大文件时使用nio的直接方式?我忽略了什么,错过了什么?任何其他方式,优化和代码改进是受欢迎的。

private static void writeData(FileChannel channel, String data) {
    ByteBuffer buffer = null;
    try {
        buffer = Charset.forName("UTF-8").encode(
                CharBuffer.wrap(data.toCharArray()));
        channel.write(buffer);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private String writeReport() {
    try {
        FileOutputStream out = new FileOutputStream(pathToFile, true);
        FileChannel channel = out.getChannel();
        // db query
        while(iterate resultset) {
             // get row result
            writeData(channel, data);
        }
    } catch(Exception e){
      //log
    } finally {
      channel.close();
      out .close();
    }
}

//pseudo code with bufferedwriter
private String writeReport(Resultset rs, String file) {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(file), 1024 * 10);
        int headerCount = 0;
        while(rs.next()) {
            String col1 = rs.getString(1);
            String col2 = rs.getString(2);
            String col3 = rs.getString(3);
            String col4 = rs.getString(4);
            String col5 = rs.getString(5);
            String colN= rs.getString(n); //nth column
            if(headerCount==0) {
                writeHeader(writer);
                headerCount++;
            }
            if(col1.equals(condition1)) {
                 writer.append(col1).append(",");
            }
            ......
            if(colN.equals(conditionN)) {
                 writer.append(colN).append(",").append(newLine());
            }
        }
    } catch(Exception e){
      //log
    } finally {
      writer.close();
    }
}

1 个答案:

答案 0 :(得分:2)

编写文件的最快方法可能是BufferedWriter.如果速度很慢,我希望看到你的代码。不应该期望NIO在这里提供任何令人吃惊的东西,你发布的代码肯定不会比BufferedWriter,更快,因为它会做更多的物理写入。