0
  • 我有一个 GB 的二进制数据文件。
  • 此文件中有许多数据部分。
  • 每个数据部分都包含在我不想要的垃圾中。
  • 在我不想要的废话中,有恒定的指标标记可以告诉我数据何时出现。
  • 我读取了一些字节,读取了我不想要的废话以找到一段数据,然后仅将数据解析到输出文件。

到目前为止,我已经做到了这一点。除了它只解析一次,一个部分,然后停止。程序仍在运行,输出文件中只有一段解析数据。所以挂了。我需要程序从最后一节继续,寻找下一个标记,然后解析下一节并继续这样做直到 eof。这是我的代码:

 private static void startParse(File inFile) throws IOException{
 boolean endOfFile = false;
 DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
 while (!endOfFile){
           try {
             int integer;
             long l;
             while((l = (integer = dis.readInt())) != MARKER) {
                 //Don't do anything
             }
             for (int i = 0; i < 11; i++){
                 dis.read();
             }

     // ***************** checksum value *****************
             byte[] checksum = new byte[2];
             checksum[0] = (byte) dis.read();
             checksum[1]    = (byte) dis.read();

     // ********************** data **********************          
             byte[] data = new byte[1016];
             for(int i = 0; i < 1016; i++){
                 data[i] = (byte) dis.read();
             }

             for (int i = 0; i < 4; i++){
                 dis.read();
             }

     // ********************** fecf **********************
             byte[] fecf = new byte[2];
             fecf[0] = (byte) dis.read();
             fecf[1] = (byte) dis.read();

     // ***************** output data ********************
             if (checksumCheck(checksum) && fecfCheck(fecf)){
                 FileOutputStream output = new FileOutputStream("ParsedData", true);
                 try{
                     output.write(data);
                 } 
                 finally{
                     output.close();
                 }
             }
             else {
                 FileOutputStream output = new FileOutputStream("ParsedData", true);
                 try{
                     output.write(36606); //TODO: Change value to bad data flag.
                 }
                 finally{
                     output.close();
                 }
             }

         }              
         catch (EOFException eof) {
             System.out.println("catch");
             endOfFile = true;
         }
     }
 dis.close();
 }
4

1 回答 1

1

dis.close()将关闭底层 FileInputStream,因此您只阅读一节。将 DataInputStream 打开和关闭移动到 while 循环之外(并在您使用时将所有关闭调用放在 finally 块中)。

于 2013-06-26T17:53:25.850 回答