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 getsize()
. But the problem is InputStream may notmarkSupported()
, so the InputStream cannot be reused in a copy file operation.