Copy InputStream, abort operation if size exceeds limit

后端 未结 6 2266
野性不改
野性不改 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:39

    I like the ByteArrayOutputStream-based solution, I cant see why it cant work

    public void copy(InputStream input, Path target) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        BufferedInputStream bis = new BufferedInputStream(input);
        for (int b = 0; (b = bis.read()) != -1;) {
            if (bos.size() > BUFFER_SIZE) {
                throw new IOException();
            }
            bos.write(b);
        }
        Files.write(target, bos.toByteArray());
    }
    

提交回复
热议问题