用Java编写数百万个小文本文件的快捷方法?

Rob*_*Rob 10 java file-io

我必须转储600万个文件,其中包含大约100-200个字符,而且速度很慢.实际的慢速部分是文件写入,如果我评论该部分(对WriteSoveraFile方法的调用)整个事情在5-10分钟内运行.事实上,我在一夜之间(16小时)运行并完成了200万条记录.

  1. 有没有更快的方法?

  2. 我是否应该更好地创建一个数组数组,然后立即将它们全部转储?(我的系统只有4 GB,不会死于这个消耗的6 GB数据吗?)

这是程序:

public static void WriteSoveraFile(String fileName, String path, String contents) throws IOException {

    BufferedWriter bw = null;

    try {
        String outputFolderPath = cloGetAsFile( GenCCD.o_OutER7Folder ).getAbsolutePath() ;
        File folder = new File( String.format("%1$s/Sovera/%2$s/", outputFolderPath, path) );  

        if (! folder.exists()) {
            folder.mkdirs();

/*          if (this.rcmdWriter != null)
              this.rcmdWriter.close();
*/        
        } 

        File file = new File( String.format("%1$s/%2$s", folder.getAbsolutePath(),fileName) );

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            bw.write(contents);
            bw.close();
        }
/*      else {
            file.delete();  // want to delete the file??  or just overwrite it??
            file.createNewFile();*/

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null) bw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

chr*_*ke- 4

这几乎肯定是操作系统文件系统问题;写入大量文件的速度很慢。我建议用 shell 和 C 语言编写一个比较测试,以了解操作系统的贡献有多大。此外,我建议进行两项重大调整:

  • 确保正在运行的系统使用 SSD。寻找文件系统日志的延迟将是开销的主要来源。
  • 多线程你的写作过程。序列化后,操作系统无法执行批量操作写入等优化,并且FileWriter可能会阻塞close()操作。

(我本来建议研究 NIO,但这些 API 似乎并没有为您的情况提供太多好处,因为设置映射缓冲区可能会带来比在这种大小下节省的开销更多的开销。)

  • @Rob 不是基于 USB 廉价内存的“闪存驱动器”,而是来自三星或英特尔的真正驱动器。要为大多数笔记本电脑添加一台,您需要 eSATA。要进行比较,请尝试将其写入 RAM 磁盘。 (2认同)