我正在创建一个实用程序,它使用RandomAccessFile将MSSQL表blob写入数据磁盘文件。它太慢了,因为我们需要总是寻找最后一个位置并写出流内容..请让我知道任何其他替代加速randomaccessfile写入。
我有超过50M的记录,目前的逻辑花了大约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();
根据您发布的代码,您只需要附加到现有文件。在追加模式下使用缓冲写入器可以更轻松,更高效地完成此操作。
因此,使用
BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardOpenOptions.CREATE, StandardOpenOptions.APPEND);
代替。
在Peter的评论之后更新:对于输出流,整个事情基本相同,只是Files
对“缓冲”部分没有很好的便利功能。 Therfore:
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND));
目前,您在每次迭代中编写大约8 Kb(8196/1024)的数据,并且每次迭代都执行阻塞并花费时间的I / O操作。尝试将其增加到至少1 Mb(10,000,000)。
byte[] buffer = new byte[10000000];