diff --git a/src/main/java/org/xerial/snappy/SnappyOutputStream.java b/src/main/java/org/xerial/snappy/SnappyOutputStream.java index 1fe3cef..d6cfda9 100755 --- a/src/main/java/org/xerial/snappy/SnappyOutputStream.java +++ b/src/main/java/org/xerial/snappy/SnappyOutputStream.java @@ -232,6 +232,9 @@ public class SnappyOutputStream extends OutputStream { * @throws IOException */ public void rawWrite(Object array, int byteOffset, int byteLength) throws IOException { + if (closed) { + throw new IOException("Stream is closed"); + } int cursor = 0; while(cursor < byteLength) { int readLen = Math.min(byteLength - cursor, blockSize - inputCursor); @@ -259,6 +262,9 @@ public class SnappyOutputStream extends OutputStream { */ @Override public void write(int b) throws IOException { + if (closed) { + throw new IOException("Stream is closed"); + } if(inputCursor >= inputBuffer.length) { compressInput(); } @@ -270,6 +276,9 @@ public class SnappyOutputStream extends OutputStream { */ @Override public void flush() throws IOException { + if (closed) { + throw new IOException("Stream is closed"); + } compressInput(); dumpOutput(); out.flush(); diff --git a/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java b/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java index e248d07..ef5f8f4 100755 --- a/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java +++ b/src/test/java/org/xerial/snappy/SnappyOutputStreamTest.java @@ -29,6 +29,7 @@ import static org.junit.Assert.*; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.IOException; import org.junit.Test; import org.xerial.snappy.buffer.BufferAllocatorFactory; @@ -193,6 +194,37 @@ public class SnappyOutputStreamTest in3.close(); } + @Test + public void writingToClosedStreamShouldThrowIOException() throws IOException { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + SnappyOutputStream os = new SnappyOutputStream(b); + os.close(); + try { + os.write(4); + fail("Expected write() to throw IOException"); + } catch (IOException e) { + // Expected exception + } + try { + os.write(new int[] { 1, 2, 3, 4}); + fail("Expected write() to throw IOException"); + } catch (IOException e) { + // Expected exception + } + } + + @Test + public void flushingClosedStreamShouldThrowIOException() throws IOException { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + SnappyOutputStream os = new SnappyOutputStream(b); + os.close(); + try { + os.flush(); + } catch (IOException e) { + // Expected exception + } + } + @Test public void longArrayCompress() throws Exception { long[] l = new long[10];