Read any file as a binary string

2019-07-13 18:22发布

问题:

As the title suggests, is there any way to read a binary representation of a given file (.txt, .docx, .exe, etc...) in Java (or any other language)?

In java, I know how to read the content of a file as is, i.e:

String line;
BufferedReader br = new BufferedReader(new FileReader("myFile.txt"));
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

But I'm not sure (if it's possible) to read a binary representation of the file itself.

回答1:

File file = new File(filePath);
byte[] bytes = new byte[(int)file.length()];
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
dataInputStream.readFully(bytes);           
dataInputStream.close();

bytes is a byte array with all of the data of the file in it