2013-06-03 1 views
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) { 
} 

long 1234567890을 bufferedInputStream에서 찾고 싶습니다. bufferedInputStream을 긴 유형으로 검색 할 수 있습니까? (필자는 매개 변수로 '읽기'가 필요한지 잘 모르겠다. 의심 스럽지만 제거 할 수있다.) bufferedInputStream은 어떻게 검색합니까? 빅 엔디안, 8 바이트 정렬.자바, 바이너리 파일 입력에서 오랫동안 검색, 8 바이트 정렬, 빅 엔디안

내가 찾는 초기 마커의 값은 1234567890입니다. 일단 값을 찾으면 변수에 2 바이트의 값을 넣을 수 있습니다. 이 2 바이트는 표식 뒤에 11 바이트 위치합니다.

답변

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

내가 찾고 있어요 초기 마커는 값 1234567890가 들어 내가 발견되면 값 I가 2 바이트의 값을 넣어하려는 변수로 변환합니다. 이 2 바이트는 표식 뒤에 11 바이트 위치합니다. –

+0

이 새로운 사양을 수행하기 위해 코드가 편집되었습니다. – Aubin

+0

retval 이후에 또 다른 1000 바이트가 있으면 어떻게됩니까? 별도의 메소드를 사용하여 1000 바이트를 어떻게 변수에 저장할 수 있습니까? –

관련 문제