[英]Best way to use RandomAccessFile is Java
我正在創建一個使用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();
根據您發布的代碼,您只需要追加到現有文件即可。 使用追加模式中的緩沖寫入器可以更輕松,更有效地完成此操作。
因此,使用
BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardOpenOptions.CREATE, StandardOpenOptions.APPEND);
代替。
在Peter的評論之后進行更新:對於輸出流,整個過程基本上是相同的,只是Files
對於“緩沖”部分沒有很好的便利功能。 因此:
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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.