Copy InputStream, abort operation if size exceeds limit

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

    Much more convenient and faster solution to check size of input stream  

        FileChannel chanel = (FileChannel) Channels.newChannel(inputStream);
        MappedByteBuffer buffer = chanel.map(FileChannel.MapMode.READ_ONLY, 0, chanel.size());
    
        System.out.println(buffer.capacity()); // bytes
    

提交回复
热议问题