首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >操作bytearray流

操作bytearray流
EN

Stack Overflow用户
提问于 2013-08-23 01:45:03
回答 1查看 170关注 0票数 0

我从命令行中读取了以下字符串(示例):

代码语言:javascript
复制
abcgefgh0111010111100000

我将其作为流处理,以到达第一个位置,即二进制(在本例中是位置9)。代码如下:

代码语言:javascript
复制
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无济于事。

EN

回答 1

Stack Overflow用户

发布于 2013-08-23 01:46:20

使用bis.reset()跟踪bis.mark(pos-1)

reset()将把流的读取游标定位在最后标记的位置(本例中为pos-1)。

来自文档:

将缓冲区重置到标记的位置。除非在构造函数中标记了另一个位置或指定了偏移量,否则标记的位置为0。

像这样重写你的循环:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18387356

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档