Read any file as a binary string

╄→гoц情女王★ 提交于 2019-12-11 03:57:48

问题


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



来源:https://stackoverflow.com/questions/31600608/read-any-file-as-a-binary-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!