-1

I am reading a large zip file but my code giving me negative array size exception

    // Simplest read of an entire file into a byte array
     // Will throw exceptions for file not found etc.
    private static byte[] loadFileAsByteArray(String path) throws IOException {
    File file = new File(path);
    InputStream is = new FileInputStream(file);
    byte[] data = new byte[(int) file. Length()];
    is.read(data);
    return data;
}

Please tell me how I can read a long zip file data in bytes

10
  • Can you add the exception to your question? NOTE: file.length() can legitimately return 0 (if you have the wrong file or a special file) and it's undefined what happens if you gave a "path" rather than file to that call. Commented Mar 16, 2021 at 6:47
  • 1
    is htere a reason you want to read the zip file instead of using ZipFile and ZipEntry that handle zip files better? Take a look at tutorials.jenkov.com/java-zip/zipfile.html Commented Mar 16, 2021 at 6:47
  • And is there a reason why you need the entire file in memory? The larger the file the worse this is as an idea, but it is never necessary. Commented Mar 16, 2021 at 6:52
  • We want to upload that zip file inside salesforce contentversion so to add body of zip file inside a version data field in contentversion we need to read the zip file in bytes Commented Mar 16, 2021 at 6:53
  • Not necessarily. What datatype are you using for the version field? And how is an entire zip file a version? Commented Mar 16, 2021 at 6:55

1 Answer 1

1

Your code has at least 1 error:
file. Length() does not deliver the result you want.
(and indeed will probably not compile at all)
Presumably what you want is file.length()

To your problem:
you can only get a negative array-size if the file you're reading is over 2,147,483,647 bytes long.
In that case, casting to int yields a negative value.

Also: even if your array is large enough to contain all the data, there is no guarantee is.read(data); will read it all in one go. You need a loop.

Finally: remember to use try-with-resources to close the InputStream & make final variables final.

How about this?:

private static byte[] loadFileAsByteArray(final String path) throws IOException {

    final File file = new File(path);

    try (final InputStream is = new FileInputStream(file)) {

        final byte[]  data = new byte[(int) file.length()]; // Cast -> -ve Array-Size?

        int           off  = 0;
        int           len;

        while (-1 != (len = is.read(data, off, data.length - off))) {
            off   +=  len;
        }
        return  data;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.