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类型?(我不确定是否需要“read”作为参数。我怀疑不需要,我可能会将其删除)。如何搜索bufferedInputStream?大端字节序,8字节对齐。
我要搜索的初始标记包含值1234567890。一旦我找到该值,我想将2个字节的值放入变量中。这2个字节位于标记后11个字节处。
1个回答

2
使用 java.io.DataInputStream.readLong() 方法可以每次读取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();
   ...
}

我要查找的初始标记包含值1234567890。一旦我找到了该值,我想将2个字节的值放入变量中。这2个字节位于标记后11个字节处。 - john stamos
现在假设在 retval 后面还有另外 1000 字节。我们如何使用另一个方法将这些 1000 字节存储到一个变量中呢? - john stamos
我想我的问题是,我该如何从我离开的地方继续进行“dis”? 我的想法是,我可能需要将“dis”从这个方法中提取出来,并在我的主函数中使用它。 然后调用一个单独的“retVal”函数和一个单独的“thousandBytes”函数? 这可行吗? - john stamos
发生什么是eof?如果没有剩余的标记,那么它会卡在while循环中吗?算了,这就是为什么要使用try catch end of file。 - john stamos
我认为我们需要将dis.read()强制转换为byte,对吗? 例如: bytes[0] = (byte) dis.read(); - john stamos
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接