读取大型对象文本文件的最快方法

3

我将超过40,000个对象存储在文本文件中。我的问题是从文本文件中读取所有对象太慢了。即使对于1,000个对象的文本文件,它也需要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");  

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

2
你尝试过使用Ehcache吗? - Neenad
1
尝试使用BufferedInputStream进行包装。ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(f))); - Eddie
2个回答

1

一个简单的优化尝试是在输入流处理中添加缓冲。按照您编写的方式,每次读取可能会访问您的磁盘。如果您减少物理读取(以更大的块),可能会看到性能提升。

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

当通过ObjectInputStream读取字节时,它们实际上是从BufferedInputStream的缓冲区中在内存中读取的。当该缓冲区变为空(全部被读取),BufferedInputStream将通过一次大的从FileInputStream读取来重新填充缓冲区。
您可以尝试使用不同的缓冲区大小来确定I/O操作数量与内存开销之间的适当平衡。

1

尝试使用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();

以上代码使用固定缓冲区大小。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接