我如何在java中读取二进制数据文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36652944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i read in binary data files in java
提问by Ionterac
So I'm doing a project for school where I need to read in a binary data file and use it to make stats, like strength and wisdom, for characters. It's set up so the first 8 bits make up one stat.
所以我正在为学校做一个项目,我需要读取一个二进制数据文件并使用它来制作角色的统计数据,比如力量和智慧。它的设置使前 8 位构成一个统计数据。
I was wondering what the actual syntax to do this is. Is it like reading text files, like this.
我想知道这样做的实际语法是什么。是不是像阅读文本文件一样,像这样。
File file = new File("CharacterStats.dat");
Scanner inputScanner = new Scanner(file);
inputScanner.next();
回答by 2ARSJcdocuyVu7LfjUnB
Instead of a Scanner you would use something like this:
你可以使用这样的东西而不是扫描仪:
File file = new File("CharacterStats.dat");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
YourClass object = (YourClass) ois.readObject();
Where the third line you are creating a new object from the stream, and casting it to the object you want. You must do this because java cannot know what object is being read in.
在第三行中,您从流中创建一个新对象,并将其转换为您想要的对象。您必须这样做,因为 java 无法知道正在读取什么对象。
EDIT: This is for reading in the binary data as serialized Objects. I may have misinterpreted your question as your "stats" being Objects.
编辑:这是为了将二进制数据作为序列化对象读入。我可能将您的问题误解为您的“统计数据”是对象。
回答by Ali Seyedi
If you're using JDK 7+ the easiest way would be:
如果您使用的是 JDK 7+,最简单的方法是:
Path path = Paths.get("CharacterStats.dat");
byte[] fileContents = Files.readAllBytes(path);
And then do with that array whatever you want.
然后随心所欲地使用该数组。
Since a byte includes 8 bits you can access the first 8 bits by fileContents[0]
and then probably control the flow of your program using bitwise operations.
由于一个字节包括 8 位,您可以访问前 8 位fileContents[0]
,然后可能使用按位运算控制程序的流程。