9

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();
Ali Seyedi
  • 1,758
  • 1
  • 19
  • 24
Ionterac
  • 91
  • 1
  • 1
  • 4

2 Answers2

16

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.

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.

Ali Seyedi
  • 1,758
  • 1
  • 19
  • 24
3

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.

EDIT: This is for reading in the binary data as serialized Objects. I may have misinterpreted your question as your "stats" being Objects.

  • Thanks. But now how do I access all the ones and zeros to use them. Sorry but I really only have experience reading in text files. – Ionterac Apr 15 '16 at 17:10
  • You don't. that's what the "readObject()" method of the ObjectInputStream does for you. It interprets the binary from the text file as a java Object. However, you then need to tell the compiler what **kind** of Object it really is, which you do by casting. – 2ARSJcdocuyVu7LfjUnB Apr 15 '16 at 17:13
  • So if I cast it as an int it will automatically convert 010010 to 18? Sorry for asking so many questions your helping a lot. – Ionterac Apr 15 '16 at 17:25