From 4b947ea90c4cffe9e396afe7f14449c5508bf191 Mon Sep 17 00:00:00 2001 From: Melissa Linkert Date: Wed, 23 Aug 2017 10:31:05 -0500 Subject: [PATCH 1/2] NIOFileHandle: reduce calls to RandomAccessFile.setLength --- src/main/java/loci/common/NIOFileHandle.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/loci/common/NIOFileHandle.java b/src/main/java/loci/common/NIOFileHandle.java index d370e588..99f527ab 100644 --- a/src/main/java/loci/common/NIOFileHandle.java +++ b/src/main/java/loci/common/NIOFileHandle.java @@ -105,6 +105,8 @@ public class NIOFileHandle extends AbstractNIOHandle { /** The original length of the file. */ private Long defaultLength; + private long effectiveLength; + // -- Constructors -- /** @@ -121,6 +123,7 @@ public NIOFileHandle(File file, String mode, int bufferSize) mapMode = FileChannel.MapMode.READ_WRITE; } raf = new RandomAccessFile(file, mode); + effectiveLength = raf.length(); channel = raf.getChannel(); byteBufferProvider = new NIOByteBufferProvider(channel, mapMode); buffer(position, 0); @@ -199,8 +202,9 @@ public int getBufferSize() { @Override public void setLength(long length) throws IOException { if (raf.length() < length) { - raf.setLength(length); + raf.setLength(length + getBufferSize()); } + effectiveLength = length; raf.seek(length - 1); buffer = null; } @@ -210,6 +214,9 @@ public void setLength(long length) throws IOException { /* @see IRandomAccess.close() */ @Override public void close() throws IOException { + if (raf.length() != length()) { + raf.setLength(length()); + } raf.close(); } @@ -225,7 +232,7 @@ public long length() throws IOException { if (defaultLength != null) { return defaultLength; } - return raf.length(); + return effectiveLength; } /* @see IRandomAccess.getOrder() */ From c2eebbdc06dbd67e056b1331bd313ae575da7bd9 Mon Sep 17 00:00:00 2001 From: Melissa Linkert Date: Wed, 23 Aug 2017 11:30:02 -0500 Subject: [PATCH 2/2] Make sure setLength is not called on a closed or read-only file --- src/main/java/loci/common/NIOFileHandle.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/loci/common/NIOFileHandle.java b/src/main/java/loci/common/NIOFileHandle.java index 99f527ab..bf291b8b 100644 --- a/src/main/java/loci/common/NIOFileHandle.java +++ b/src/main/java/loci/common/NIOFileHandle.java @@ -214,7 +214,7 @@ public void setLength(long length) throws IOException { /* @see IRandomAccess.close() */ @Override public void close() throws IOException { - if (raf.length() != length()) { + if (isReadWrite && channel.isOpen() && raf.length() != length()) { raf.setLength(length()); } raf.close();