Java 操纵旁路流
我从命令行读取以下字符串(示例): 我将其作为一个流处理,以到达第一个二进制位置(在本例中是位置9)。 代码如下:Java 操纵旁路流,java,inputstream,bytearrayinputstream,Java,Inputstream,Bytearrayinputstream,我从命令行读取以下字符串(示例): 我将其作为一个流处理,以到达第一个二进制位置(在本例中是位置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)=='
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)
或重置没有帮助。遵循bis.mark(pos-1)
,使用bis.reset()
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) {
}
此代码存储上次读取字节的位置。您的代码以前不工作,因为它在读取所需字节后存储位置。没有帮助-将此添加到末尾,并从第二个二进制文件而不是第一个二进制文件开始打印。二.标记(1号位置);二、重置();System.out.println(“数据开始于:“+pos”);字节[]arr=新字节[3];尝试{bis.read(arr);System.out.println(新字符串(arr));}catch(异常x){}编辑。这就是您需要使用它的方式。也不起作用-在本例中,流已经读取了第一个二进制文件;我用这个精确的循环测试了你的代码,它看起来很有效。8到10个小时后,我会再给你测试一次。看看我是不是在什么地方出错了。睡觉时间,明天见:)再次编辑。该循环有效,您可能没有在循环后删除
标记
调用。试试我上面的代码。它会起作用的。
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) {
}