使用RandomAccessFile的最佳方法是Java

时间:2018-09-06 05:06:46

标签: java performance large-data randomaccessfile

我正在创建一个使用RandomAccessFile将MSSQL表Blob写入数据磁盘文件的实用程序。它太慢了,因为我们需要始终寻找最后一个位置并写入流内容..请让我知道其他任何方法来加快randomaccessfile的写入速度。

我有超过5000万条记录,而根据当前逻辑,这大约花费了10个小时。

我的代码块是这样的:

RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
InputStream inputStream = null;

while (rows.hasNext()) {
    Row row = rows.next();
    inputStream = (InputStream) row.getValues()[0];
    offset = randomAccessFile.length();
    byte[] buffer = new byte[8196];
    int count;
    randomAccessFile.seek(offset);
    randomAccessFile.setLength(offset);
    while ((count = inputStream.read(buffer)) != -1) {
        randomAccessFile.write(buffer, 0, count);
    }
}
randomAccessFile.close();   

2 个答案:

答案 0 :(得分:2)

根据您发布的代码,您只需要追加到现有文件即可。使用附加模式下的缓冲写入器可以更轻松,更有效地完成此操作。

因此,使用

mm-dd-yyyy

相反。

在Peter的评论之后进行更新:对于输出流,整个过程基本上是相同的,只是BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardOpenOptions.CREATE, StandardOpenOptions.APPEND); 对于“缓冲”部分没有很好的便捷功能。因此:

Files

答案 1 :(得分:0)

当前,您在每次迭代中大约写入8 Kb(8196/1024)数据,并且每个迭代都执行一个I / O操作,该操作阻塞并占用时间。尝试将其大约增加到至少1 Mb(10,000,000)。

byte[] buffer = new byte[10000000];