Created
January 17, 2017 16:24
-
-
Save mardambey/8968727834e6545beffe8148185b1ccb to your computer and use it in GitHub Desktop.
An output stream that throws an exception if more than the given bytes have been written to it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.{FilterOutputStream, IOException, OutputStream} | |
class LimitedOutputStream(out: OutputStream , maxBytes: Long) extends FilterOutputStream(out) { | |
private var bytesWritten: Long = 0L | |
@throws(classOf[IOException]) | |
override def write(b: Int) { | |
ensureCapacity(1) | |
super.write(b) | |
} | |
@throws(classOf[IOException]) | |
override def write(b: Array[Byte]) { | |
ensureCapacity(b.length) | |
super.write(b) | |
} | |
@throws(classOf[IOException]) | |
override def write(b: Array[Byte], off: Int, len: Int) { | |
ensureCapacity(len) | |
super.write(b, off, len) | |
} | |
@throws(classOf[IOException]) | |
private def ensureCapacity(len: Int) { | |
val newBytesWritten = bytesWritten + len | |
if (newBytesWritten > maxBytes) | |
throw new IOException("File size exceeded: " + newBytesWritten + " > " + maxBytes) | |
bytesWritten = newBytesWritten | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment