Copy InputStream, abort operation if size exceeds limit

后端 未结 6 2260
野性不改
野性不改 2020-12-18 19:08

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 cop         


        
6条回答
  •  一生所求
    2020-12-18 19:25

    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.

提交回复
热议问题