Skip to content

Instantly share code, notes, and snippets.

@mardambey
Created January 17, 2017 16:24
Show Gist options
  • Save mardambey/8968727834e6545beffe8148185b1ccb to your computer and use it in GitHub Desktop.
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.
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