读取任何文件作为二进制字符串 [英] Read any file as a binary string

查看:132
本文介绍了读取任何文件作为二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的,有没有什么办法来读取一个给定文件的二进制重新presentation(txt文件,.DOCX,.EXE等)在Java中(或任何其他语言)<? / p>

在Java中,我知道如何读取文件的内容是,即:

 串线;
BR的BufferedReader =新的BufferedReader(新的FileReader(myfile.txt的));
而((行= br.readLine())!= NULL){
    的System.out.println(线);
}

但我不知道(如果可能的话)来读取文件本身的二进制重新presentation。


解决方案

 文件文件=新的文件(文件路径);
字节[]字节=新字节[(INT)file.length()];
DataInputStream以DataInputStream所=新DataInputStream所(新的BufferedInputStream(新的FileInputStream(文件路径)));
dataInputStream.readFully(字节);
dataInputStream.close();

字节是一个字节数组的所有文件的数据在它

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.

解决方案

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

这篇关于读取任何文件作为二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆