Remember that the answers given here assume that the file length is less than or equal to Integer.MAX_VALUE (2147483647).
If you are reading from a file, you can do something like this:
File file = new File("myFile"); byte[] fileData = new byte[(int) file.length()]; DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData); dis.close();
UPDATE (May 31, 2014):
Java 7 adds some new features to the java.nio.file package, which you can use to make this example a few lines shorter. See the readAllBytes () method in the java.nio.file.Files class. Here is a quick example:
import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; // ... Path p = FileSystems.getDefault().getPath("", "myFile"); byte [] fileData = Files.readAllBytes(p);
Android has support for this, starting with Api Level 26 (8.0.0, Oreo).
James K Polk Aug 30 2018-11-21T00: 00Z
source share