0

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?

user1120946
  • 171
  • 1
  • 2
  • 13
  • 1
    The read-position gets incremented. – tkausl Aug 28 '16 at 05:34
  • @tkausl: So is it correct way to check file size using IOUtils.read()? – user1120946 Aug 28 '16 at 05:41
  • 1
    No. http://stackoverflow.com/questions/2149785/get-size-of-folder-or-file – tkausl Aug 28 '16 at 05:44
  • If you are going to read the content anyway, why read through to find size first? Just load the data and check the size loaded. – Andreas Aug 28 '16 at 06:43
  • @tkausl: I don't want to convert it to java.io.file for checking the size. I've to pass the InputStream to upload image file to s3 bucket. (Updated my question). – user1120946 Aug 28 '16 at 08:30
  • You are writing some very strange code here. You should be looking at `new File("/path/to/image.jpg").length()`, instead of reading the entire file just to find out what its length is. You're just wasting time and space here. – user207421 Aug 28 '16 at 10:25

1 Answers1

4

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

Community
  • 1
  • 1
ophychius
  • 2,623
  • 2
  • 27
  • 49
  • Thank you @ophychius for the info. Actually I'm getting an image from Jersey REST as an InputStream and I've to pass that InputStream to upload to s3 bucket. I think it will be bit odd to convert that to java.io.file just to check size. – user1120946 Aug 28 '16 at 08:10
  • @user1120946 The code you posted already uses `java.io.File`. If that isn't the real code, your question is futile, and if your intent is to load the file twice, ditto. – user207421 Aug 28 '16 at 10:32