Anonymous
Anonymous

Reputation: 1

Is it possible to store all bytes from file to array of bytes?

Just as the title, is it possible to store all bytes from file to array of bytes without getting java heap space error?

Upvotes: 0

Views: 76

Answers (2)

Salvioner
Salvioner

Reputation: 333

As suggested by assylias, the 100% Java way to do this is with Files.readAllBytes(path).

Heap space errors depend on the file size and the amount of free memory in the JVM heap; you need to verify that the first is lower than the second before reading it:

File file = new File(path);
bytes[] bytes;
if (file.length > Runtime.getRuntime().freeMemory()) {
    // warn about reading
} else {
    bytes = Files.readAllBytes(path)
    // do stuff with 'bytes'
}

Upvotes: 0

Dima
Dima

Reputation: 8662

yes, you can use IOUtils.toByteArray(InputStream input) to store it.

also, if its a big file, you can increase java heap space by executing it with vm arguments:

java -Xmx6g myprogram

or

java -jar -Xmx6g myprogram.jar

the 6g means 6 Gigabytes of heap

Upvotes: 1

Related Questions