卢声远 Shengyuan Lu 卢声远 Shengyuan Lu - 4 months ago 38
Java Question

Copy InputStream, abort operation if size exceeds limit

I tried to copy an InputStream to a File, and abort the copy if the size of InputStream is greater than 1MB.
In Java7, I wrote code as below:

public void copy(InputStream input, Path target) {
OutputStream out = Files.newOutputStream(target,
StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
boolean isExceed = false;
try {
long nread = 0L;
byte[] buf = new byte[BUFFER_SIZE];
int n;
while ((n = input.read(buf)) > 0) {
out.write(buf, 0, n);
nread += n;
if (nread > 1024 * 1024) {// Exceed 1 MB
isExceed = true;
break;
}
}
} catch (IOException ex) {
throw ex;
} finally {
out.close();
if (isExceed) {// Abort the copy
Files.deleteIfExists(target);
throw new IllegalArgumentException();
}
}}



  • First question: is there any better solution for it?

  • Second question: my other solution - Before the copy operation, I calculate the size of this InputStream. So I copy the InputStream to
    ByteArrayOutputStream
    then get
    size()
    . But the problem is InputStream may not
    markSupported()
    , so the InputStream cannot be reused in a copy file operation.


Answer

First question: is there any better solution for it?

Not really. Certainly, not significantly better.

Second question: my other solution - Before the copy operation, I calculate size of InputStream. So I copy the InputStream to ByteArrayOutputStream then get size(). But the problem is InputStream may not markSupported(), so the InputStream cannot be reused in copy file operation.

Leaving aside that the above is a statement not a question ...

If you have copied the bytes to the ByteArrayOutputStream, you can then create a ByteArrayInputStream from the byte array returned by baos.toByteArray(). So you don't need to mark / reset the original stream.

However, that is a pretty ugly way of implementing this. Not least because you are reading and buffering the entire input stream anyway.

Comments