将任何文件作为二进制字符串读取

3

正如标题所示,是否有办法在Java(或其他语言)中读取给定文件(.txt,.docx,.exe等)的二进制表示?

在Java中,我知道如何按原样读取文件内容,即:

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

但我不确定是否可以读取文件本身的二进制表示。


可能是Java文件转二进制转换的重复问题。 - Roberto Anić Banić
1
Java文件转二进制的重复问题:https://dev59.com/V1rUa4cB1Zd3GeqPjm3Y - Roberto Anić Banić
你的问题不够清晰。你是在问如何将文件读取为字节数组吗?还是想要将文件作为完全由 '0' 和 '1' 字符组成的字符串进行读取? - VGR
1个回答

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 是一个包含文件所有数据的字节数组


1
或者,只需使用Files.readAllBytes(Paths.get(filePath)) - VGR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接