8227080: (fs) Files.newInputStream(...).skip(n) is slow

Reviewed-by: sbordet, rriggs, fweimer
This commit is contained in:
Brian Burkhalter 2019-07-03 14:37:19 -07:00
parent 5b24465467
commit c6c82dd736
2 changed files with 61 additions and 7 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,7 +29,7 @@ import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.util.Objects;
/**
* This class is defined here rather than in java.nio.channels.Channels
@ -87,10 +87,8 @@ public class ChannelInputStream
public synchronized int read(byte[] bs, int off, int len)
throws IOException
{
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0)
Objects.checkFromIndexSize(off, len, bs.length);
if (len == 0)
return 0;
ByteBuffer bb = ((this.bs == bs)
@ -119,6 +117,26 @@ public class ChannelInputStream
return 0;
}
public synchronized long skip(long n) throws IOException {
// special case where the channel is to a file
if (ch instanceof SeekableByteChannel && n > 0) {
SeekableByteChannel sbc = (SeekableByteChannel)ch;
try {
long pos = sbc.position();
long size = sbc.size();
if (pos >= size) {
return 0L;
}
n = Math.min(n, size - pos);
sbc.position(pos + n);
return sbc.position() - pos;
} catch (ClosedChannelException cce) {
throw new IOException(cce);
}
}
return super.skip(n);
}
public void close() throws IOException {
ch.close();
}