【问题标题】:Fastest way of reading large object-text file读取大型对象文本文件的最快方法
【发布时间】:2015-10-20 03:44:49
【问题描述】:

我将 40,000 多个对象存储到一个文本文件中。我的问题是从文本文件中读取所有对象太慢了。 1000 个对象的文本文件甚至需要 4349 毫秒。

这是从文本文件中读取对象。

long startR = System.currentTimeMillis();

try{
    ois = new ObjectInputStream(new FileInputStream(f));
    code_from_file.clear();
    Codes obj = new Codes();

    while( (obj = (Codes) ois.readObject()) != null){   
        if(obj instanceof Codes){
            code_from_file.add(obj);
        }
    }

}catch (EOFException ex){ 

} catch (ClassNotFoundException ex) {
    ex.printStackTrace();
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
} finally{
    try {
        if (ois != null){
            ois.close();
        }
    } catch (IOException ex){
        ex.printStackTrace();
    }
}

long endR = System.currentTimeMillis();
System.out.println("Read code from file : " + (endR - startR) + "ms");  

有没有更快的方法来解决这个问题?

【问题讨论】:

  • 你试过 ehcache 吗?
  • 尝试用缓冲的输入流包装它。 ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f)));

标签: java file-handling


【解决方案1】:

一个简单的优化尝试是为您的输入流处理添加缓冲。在您编写它时,每次读取都可能会影响您的磁盘。如果您执行较少的物理读取(以较大的块),您可能会看到性能提升。

int bufferSize = 16 * 1024;
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f), bufferSize));

当通过 ObjectInputStream 读取字节时,它们实际上是从 BufferedInputStream 的缓冲区中读取到内存中的。当此缓冲区变空(已全部读取)时,BufferedInputStream 将在从 FileInputStream 进行一次大读取时重新填充缓冲区。

您可以试验不同的缓冲区大小,以确定 I/O 操作数与内存开销之间的适当平衡。

【讨论】:

    【解决方案2】:

    尝试使用 NIO,它有很多增强和缓冲

        RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
        FileChannel inChannel = aFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int read;
        while((read = inChannel.read(buffer)) != -1){
            os.write(buffer, 0, read);
        }
        inChannel.close();
        aFile.close();
    

    上面的代码是缓冲区大小的固定宽度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-03
      • 2012-08-26
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多