首页 文章

Java,在二进制文件输入中搜索长,8字节对齐,大端

提问于
浏览
3
public static void main(String[] args) {
   File inFile = null;
   if (0 < args.length) {
      inFile = new File(args[0]);
   }
   BufferedInputStream bStream = null;
   try {
      int read;
      bStream = new BufferedInputStream(new FileInputStream(inFile));
      while ((read = bStream.read()) > 0) {
         getMarker(read, bStream);
         System.out.println(read);
      }
   }
   catch (IOException e) {
      e.printStackTrace();
   }
   finally {
      try {
         if (bStream != null)bStream.close();
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

private static void getMarker(int read, BufferedInputStream bStream) {
}

我想在bufferedInputStream中找到长1234567890 . 我可以在bufferedInputStream中搜索long类型吗? (我不确定我是否需要'读'作为参数 . 我对此表示怀疑,我可能会删除它 . 如何搜索bufferedInputStream?大端,8字节对齐 .

我正在搜索的初始标记包含值1234567890.一旦找到该值,我想将2个字节的值放入变量中 . 这两个字节位于标记后的11个字节 .

1 回答

  • 2

    使用方法java.io.DataInputStream.readLong(),可以每8字节读取8个字节的数据 . 但问题是:文件只包含长数据还是其他数据?

    如果数据可能在任何地方,我们必须读取从偏移量0,1,2开始的文件的8倍,依此类推 .

    class FuzzyReaderHelper {
    
       public static final long MAGIC_NUMBER = 1234567890L;
    
       public static DataInputStream getStream( File source ) {
          boolean magicNumberFound = false;
          for( int offset = 0; !magicNumberFound && offset < 8; ++offset ) {
             dis = new DataInputStream( new FileInputStream( source ));
             for( int i = 0; i < offset; ++i ) {
                dis.read();
             }
             try {
                long l;
                while(( l = dis.readLong()) != MAGIC_NUMBER ) {
                   /* Nothing to do... */
                }
                magicNumberFound = true;
                for( int i = 0; i < 11; ++i ) {
                   dis.read();
                }
                return dis;
             }
             catch( EOFException eof ){}
             dis.close();
          }
       // choose:
          throw new IllegalStateException( "Incompatible file: " + source );
       // or
          return null; 
       }
    }
    

    接下来的步骤取决于您:

    DataInputStream dis = FuzzyReaderHelper.getStream( new File( root, "toto.dat" ));
    if( dis != null ) {
       byte[] bytes = new byte[2];
       bytes[0] = dis.read();
       bytes[1] = dis.read();
       ...
    }
    

相关问题