简体   繁体   中英

What happens to InputStream after IOUtils.read()

I'm writing a code to validate max file size.

public static void main(String[] args) throws IOException {

    final InputStream inputStream = new FileInputStream(new File("/path/to/image.jpg"));

    System.out.println("initial: " + inputStream.read());

    int arr = IOUtils.read(inputStream, new byte[2000001]);
    if (arr == 2000001) {
        System.out.println("file size greater than limit");
    }
    System.out.println("after: " + inputStream.read());
}

Output

initial: 255
file size greater than limit
after: 21

Question is what happens to InputStream when it's passed to IOUtils.read()? Moving forward I've to save InputStream as image, when I pass the same InputStream reference to save method upload method of s3 bucket, corrupt image gets saved. Can anybody give me an idea what's going on?

Once you read something from an InputStream it is 'gone'. The read position moves up along the input. So while you are busy to try counting the bytes in your file you are at the same time losing data because it is not being stored. So once you pass the InputStream reference to save the file your reader is not at the beginning of the stream/file anymore, resulting in a corrupted file.

You can get the size of the file in a different way.

java.io.File file = new java.io.File("example.file");
file.length();

Than if the file is not too large you can move on to saving the file. For checking file size also check the link offered by @tkausl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM