From a9503284d3f3c1b75630a60d7641e66fa44556b2 Mon Sep 17 00:00:00 2001 From: Jake Wharton Date: Tue, 13 Feb 2018 23:56:17 -0500 Subject: [PATCH] Transfer to/from FileChannel directly from Buffer. --- .../okhttp3/internal/cache2/FileOperator.java | 40 +++---------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/okhttp/src/main/java/okhttp3/internal/cache2/FileOperator.java b/okhttp/src/main/java/okhttp3/internal/cache2/FileOperator.java index b1326cddc9a6..b4ce63012fa7 100644 --- a/okhttp/src/main/java/okhttp3/internal/cache2/FileOperator.java +++ b/okhttp/src/main/java/okhttp3/internal/cache2/FileOperator.java @@ -17,7 +17,6 @@ import java.io.EOFException; import java.io.IOException; -import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import okio.Buffer; import okio.Okio; @@ -35,10 +34,6 @@ * */ final class FileOperator { - private static final int BUFFER_SIZE = 8192; - - private final byte[] byteArray = new byte[BUFFER_SIZE]; - private final ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray); private final FileChannel fileChannel; FileOperator(FileChannel fileChannel) { @@ -50,22 +45,9 @@ public void write(long pos, Buffer source, long byteCount) throws IOException { if (byteCount < 0 || byteCount > source.size()) throw new IndexOutOfBoundsException(); while (byteCount > 0L) { - try { - // Write bytes to the byte[], and tell the ByteBuffer wrapper about 'em. - int toWrite = (int) Math.min(BUFFER_SIZE, byteCount); - source.read(byteArray, 0, toWrite); - byteBuffer.limit(toWrite); - - // Copy bytes from the ByteBuffer to the file. - do { - int bytesWritten = fileChannel.write(byteBuffer, pos); - pos += bytesWritten; - } while (byteBuffer.hasRemaining()); - - byteCount -= toWrite; - } finally { - byteBuffer.clear(); - } + long bytesWritten = fileChannel.transferFrom(source, pos, byteCount); + pos += bytesWritten; + byteCount -= bytesWritten; } } @@ -78,19 +60,9 @@ public void read(long pos, Buffer sink, long byteCount) throws IOException { if (byteCount < 0) throw new IndexOutOfBoundsException(); while (byteCount > 0L) { - try { - // Read up to byteCount bytes. - byteBuffer.limit((int) Math.min(BUFFER_SIZE, byteCount)); - if (fileChannel.read(byteBuffer, pos) == -1) throw new EOFException(); - int bytesRead = byteBuffer.position(); - - // Write those bytes to sink. - sink.write(byteArray, 0, bytesRead); - pos += bytesRead; - byteCount -= bytesRead; - } finally { - byteBuffer.clear(); - } + long bytesRead = fileChannel.transferTo(pos, byteCount, sink); + pos += bytesRead; + byteCount -= bytesRead; } } }