Search code examples
javaiodatainputstream

Binary I/O Skipping the bytes and printing only the UTF types


So here is my problem : I need to read some data from a .dat file, the problem being that not all things are saved the same (some UTF, Int, Double), so I can't just readUTF() in a loop until it's done because it will stumble upon an Int and give me an error. One thing I do know is that the order of the things written in the .dat file, and they go like this: UTF, Int, Double, Double, Double. Here is the code I have so far :

import java.io.*;

public class BytePe1 {
   public static void main(String[] args) {
      try {
         FileInputStream fis = new  FileInputStream("ClassList.dat");
         BufferedInputStream bis = new BufferedInputStream( fis );
         DataInputStream dis = new DataInputStream(bis);

         String studentName;
         int studentNumber;

         //while(dis.readLine() != null) {
            System.out.println("Name");
            System.out.println(dis.readUTF());
            System.out.println(dis.readInt());
            System.out.println(dis.readDouble());
            System.out.println(dis.readDouble());
            System.out.println(dis.readDouble());
            //System.out.println(dis.readUTF());
            //And I would need to repeat these steps above but I don't know how many
            //Files there actually are, so I would like to not just spam this until I see errors
         //}
         dis.close();
      }
      catch(Exception e) {
         System.out.println("Exception: " + e.getMessage());
      }
   }
}

This will output the correct things but I don't know how many things I have saved in that file, and thats what I would like to know; is it possible to skip some parts of the file and just print all of the names and then int's and so on. One small part of the reading


Solution

  • Java's RandomAccessFile has two useful methods, getFilePointer() and length(). Whenever getFilePointer() is less than length(), there is data available to read.

    try {
        RandomAccessFile raf = new RandomAccessFile("ClassList.dat", "r");
        while (raf.getFilePointer() < raf.length()) {
            System.out.println(raf.readUTF());
            System.out.println(raf.readInt());
            System.out.println(raf.readDouble());
            System.out.println(raf.readDouble());
            System.out.println(raf.readDouble());
        }
        raf.close();
    } catch (Exception e) {
        e.printStackTrace();
    }