二进制I/O跳过字节并仅打印UTF类型



所以这是我的问题:我需要从.dat文件中读取一些数据,问题是并非所有事物都保存相同(某些UTF,int,double(,所以在完成之前,我不能只是循环中的readUTF(),因为它会偶然发现INT并给我一个错误。我确实知道的一件事是,在.dat文件中写的内容的顺序,它们会像这样:UTF,int,double,double,double。这是我到目前为止的代码:

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

这将输出正确的内容,但我不知道我在该文件中保存了多少东西,这就是我想知道的。是否可以跳过文件的某些部分,只打印所有名称,然后打印int等等。阅读的一小部分

java的RandomAccessFile具有两个有用的方法,GetFilePointer((和Length((。每当getFilePointer((小于长度((时,都有可以读取的数据。

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

最新更新