2013-08-22 66 views
0

予讀取命令行下面的字符串(例如):操縱的ByteArray流

abcgefgh0111010111100000 

予處理此作爲流在其爲二進制的第一位置到達(在這種情況下,它是9位)。 的代碼如下:

String s=args[0]; 
    ByteArrayInputStream bis=new ByteArrayInputStream(s.getBytes()); 
    int c; 
    int pos=0; 
    while((c=bis.read())>0) 
    { 
     if(((char)c)=='0' || ((char)c)=='1') break; 
     pos++; 
    } 

bis.mark(pos-1);\\this does not help 
    bis.reset();\\this does not help either 
    System.out.println("Data begins from : " + pos); 
    byte[] arr=new byte[3]; 
    try{ 
    bis.read(arr); 
    System.out.println(new String(arr)); 
    }catch(Exception x){} 

現在Arraystream將開始從位置10( '1')讀數。
如何讓它退回一個位置,實際開始再次從位置9的第一個二進制數字('0')開始讀取。
bis.mark(pos-1)或重置不起作用。

回答

0

關注bis.mark(pos-1),與bis.reset()

復位()將定位流的在最後標記位置讀取光標

從文檔(在此情況下pos-1):

復位緩衝器到標記的位置。標記的位置是0,除非在構造函數中標記了另一個位置或指定了偏移量。

改寫你的循環,像這樣:

String s = "abcgefgh0111010111100000"; 
ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes()); 
int c; 
int pos = 0; 
while (true) { 
    bis.mark(10); 
    if ((c = bis.read()) > 0) { 
     if (((char) c) == '0' || ((char) c) == '1') 
      break; 
     pos++; 
    } else 
     break; 
} 
bis.reset();// this does not help either 
System.out.println("Data begins from : " + pos); 
byte[] arr = new byte[3]; 
try { 
    bis.read(arr); 
    System.out.println(new String(arr)); 
} catch (Exception x) { 
} 

此代碼存儲最後一次讀取字節的位置。你的代碼之前沒有工作,因爲它在之後存儲了位置你想要的字節被讀取。

+0

沒有幫助 - 將其添加到最後,它從第二個二進制文件開始打印,而不是第一個。 bis.mark(pos-1); \t bis.reset(); System.out.println(「Data beginning from:」+ pos); \t byte [] arr = new byte [3]; \t嘗試{ \t bis.read(arr); \t System.out.println(new String(arr)); \t} catch(Exception x){} – IUnknown

+0

已編輯。這就是你需要使用它的方式。 –

+0

也不管用 - 在這種情況下,流已經讀取了第一個二進制文件;並且不能被後退一個位置。 – IUnknown