I have the following piece of code that uses the java 7 features like java.nio.file.Files and java.nio.file.Paths
import java.io.File;
impor
You can read all bytes of a file into byte array even in Java 6 as described in an answer to a related question:
import java.io.RandomAccessFile;
import java.io.IOException;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
if (f.length() > Integer.MAX_VALUE)
throw new IOException("File is too large");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
if (f.getFilePointer() != f.length())
throw new IOException("File length changed while reading");
I added the checks leading to exceptions and the change from read
to readFully
, which was proposed in comments under the original answer.