3

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.

CIOC
  • 1,385
  • 3
  • 19
  • 48
  • possible duplicate of [Java File to Binary Conversion](http://stackoverflow.com/questions/7119141/java-file-to-binary-conversion) – Roberto Anić Banić Jul 24 '15 at 01:15
  • 1
    Duplicate of http://stackoverflow.com/questions/7119141/java-file-to-binary-conversion – Roberto Anić Banić Jul 24 '15 at 01:16
  • Your question is unclear. Are you asking how to read a file as a byte array? Do you want to read the file as a String consisting entirely of '0' and '1' characters? – VGR Jul 24 '15 at 02:49

1 Answers1

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

StephenG
  • 2,851
  • 1
  • 16
  • 36
  • 1
    Or, just use [Files.readAllBytes(Paths.get(filePath))](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllBytes-java.nio.file.Path-). – VGR Jul 24 '15 at 10:26