我如何在Java中读取二进制数据文件

我如何在Java中读取二进制数据文件

本文介绍了我如何在Java中读取二进制数据文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在为学校做一个项目,我需要读取一个二进制数据文件,并使用它来为角色制作诸如力量和智慧之类的统计数据.设置好后,前8位就构成一个状态.

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.

我想知道执行此操作的实际语法是什么.就像这样读取文本文件吗?

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

推荐答案

如果您使用的是JDK 7+,最简单的方法是:

If you're using JDK 7+ the easiest way would be:

Path path = Paths.get("CharacterStats.dat");
byte[] fileContents =  Files.readAllBytes(path);

然后根据需要使用该数组.

And then do with that array whatever you want.

由于字节包含8位,因此您可以通过fileContents[0]访问前8位,然后可能使用按位操作.

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.

这篇关于我如何在Java中读取二进制数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 08:51