2013-08-22 54 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