我从命令行中读取了以下字符串(示例):
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)或reset无济于事。
发布于 2013-08-23 01:46:20
使用bis.reset()跟踪bis.mark(pos-1)。
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) {
}此代码存储最后读取的字节的位置。你的代码之前没有工作,因为它是在你想要的字节被读取之后存储位置的。
https://stackoverflow.com/questions/18387356
复制相似问题