diff options
author | Nick Burch <nick@apache.org> | 2015-05-04 09:15:48 +0000 |
---|---|---|
committer | Nick Burch <nick@apache.org> | 2015-05-04 09:15:48 +0000 |
commit | a874e223af546e5d32d2bc9aae4520a9a97c2def (patch) | |
tree | e139d5e5f9966976c4c29f1aa728c627afa7c778 /src/java/org/apache/poi/util/IOUtils.java | |
parent | 7c44ed1f03a643bb60955f0707813f8107a377fd (diff) | |
download | poi-a874e223af546e5d32d2bc9aae4520a9a97c2def.tar.gz poi-a874e223af546e5d32d2bc9aae4520a9a97c2def.zip |
If an empty stream or file is given to WorkbookFactory.create, give a more informative exception - EmptyFileException
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1677562 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'src/java/org/apache/poi/util/IOUtils.java')
-rw-r--r-- | src/java/org/apache/poi/util/IOUtils.java | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/java/org/apache/poi/util/IOUtils.java b/src/java/org/apache/poi/util/IOUtils.java index 4f18214c46..e0f2bd16c1 100644 --- a/src/java/org/apache/poi/util/IOUtils.java +++ b/src/java/org/apache/poi/util/IOUtils.java @@ -22,11 +22,14 @@ import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.util.zip.CRC32; import java.util.zip.Checksum; +import org.apache.poi.EmptyFileException; + public final class IOUtils { private static final POILogger logger = POILogFactory @@ -35,6 +38,34 @@ public final class IOUtils { private IOUtils() { // no instances of this class } + + /** + * Peeks at the first 8 bytes of the stream. Returns those bytes, but + * with the stream unaffected. Requires a stream that supports mark/reset, + * or a PushbackInputStream. If the stream has >0 but <8 bytes, + * remaining bytes will be zero. + * @throws EmptyFileException if the stream is empty + */ + public static byte[] peekFirst8Bytes(InputStream stream) throws IOException, EmptyFileException { + // We want to peek at the first 8 bytes + stream.mark(8); + + byte[] header = new byte[8]; + int read = IOUtils.readFully(stream, header); + + if (read < 1) + throw new EmptyFileException(); + + // Wind back those 8 bytes + if(stream instanceof PushbackInputStream) { + PushbackInputStream pin = (PushbackInputStream)stream; + pin.unread(header); + } else { + stream.reset(); + } + + return header; + } /** * Reads all the data from the input stream, and returns the bytes read. |