0

I am currently doing a job where I have to make a MIPS simulator,
I had already done the project in C, but now I have to do in Java, and how to use a binary file as input, had a function in C that returned a value for me to know whether the file is valid or not.
The function was: fread(&memoTextSize, sizeof(int), 1, arch);
And I need something to do just that above but in Java.
I am very grateful if anyone can help me.
Thank!

user3655060
  • 11
  • 2
  • 4
  • To read from a binary file, use a `java.io.FileInputStream`. See [Java Tutorial: I/O](https://docs.oracle.com/javase/tutorial/essential/io/). – Jesper Dec 03 '14 at 19:43

2 Answers2

2

You're probably going to want to use BufferedInputStream. Here is an example:

import java.io.*;

class TestBinaryFileReading {

  static public void main(String[] args) throws IOException {  
    DataInputStream data_in = new DataInputStream(
        new BufferedInputStream(
            new FileInputStream(new File("binary_file.dat"))));
    while(true) {
      try {
        int t = data_in.readInt();//read 4 bytes

        System.out.printf("%08X ",t); 

        // change endianness "manually":
        t = (0x000000ff & (t>>24)) | 
            (0x0000ff00 & (t>> 8)) | 
            (0x00ff0000 & (t<< 8)) | 
            (0xff000000 & (t<<24));
        System.out.printf("%08X",t); 
        System.out.println();
      } 
      catch (java.io.EOFException eof) {
        break;
      }
    } 
    data_in.close();
  }
}

From How to read binary file created by C/Matlab using JAVA

Community
  • 1
  • 1
Jase Pellerin
  • 397
  • 1
  • 2
  • 13
0

Alternative:

ByteBuffer byteBuffer = ByteBuffer.wrap(Files.readAllBytes(Paths.get(path)));
byteBuffer = byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
int size = byteBuffer.asIntBuffer().get();
Remy Mellet
  • 1,675
  • 20
  • 23