简体   繁体   English

我如何读取java中的二进制数据文件

[英]How do i read in binary data files in java

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();

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位,您可以通过fileContents[0]访问前8位,然后可能使用按位运算控制程序的流程。

Instead of a Scanner you would use something like this: 您可以使用以下内容代替Scanner:

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. 我可能误解了你的问题,因为你的“统计数据”是对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM