简体   繁体   English

IOUtils.read()之后InputStream会发生什么

[英]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()? 问题是将InputStream传递给IOUtils.read()时会发生什么? Moving forward I've to save InputStream as image, when I pass the same InputStream reference to 继续前进,当我将相同的InputStream引用传递给时,我必须将InputStream保存为图像 save method 保存方法 upload method of s3 bucket, corrupt image gets saved. s3存储桶的上传方法,保存损坏的图像。 Can anybody give me an idea what's going on? 有人可以告诉我发生了什么吗?

Once you read something from an InputStream it is 'gone'. 从InputStream读取内容后,它就“消失了”。 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. 因此,一旦传递InputStream引用以保存文件,您的阅读器就不再位于流/文件的开头,从而导致文件损坏。

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 要检查文件大小,还请检查@tkausl提供的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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