我有一个阅读器,它以流的形式接收消息包(ByteArrayInputStream)。
每个包包含由英文字符和二进制数字组成的数据。
adghfjiyromn1000101010100......什么是最有效的方式来复制(而不是剥离)字符从这个流作为一个序列。因此,上述数据包的预期输出将是(不修改原始流):
adghfjiyromn我不仅关心逻辑,而且关心要使用的确切的流操作例程;考虑到读者每秒钟会读取大约3-4个数据包。
它还有助于说明为什么我们更喜欢特定的数据类型(byte[]、char[]或string)来解决这个问题。
发布于 2013-08-17 07:13:02
我认为最好的方法是逐字节读取ByteArrayInputStream:
ByteArrayInputStream msg = ...
int c;
String s;
while ((c = msg.read())!= -1) {
char x = (char) c;
if (x=='1' || x=='0') break;
s += x;
}发布于 2013-08-17 06:04:06
我认为这是最好的方法:
1-将ByteArrayInputStream转换为String (或StringBuffer) 2-查找0或1 3的第一个索引-使用子字符串(0,FIRST_INDEX )
发布于 2013-08-17 09:05:17
您:每个包包含由英文字符和二进制数字组成的数据。Me :数据在bytearrayinputstream中,因此一切都是二进制的。你的1000101010100.字符是“1”和“0”吗?
如果是
ByteArrayInputStream msg = //whatever
int totalBytes = msg.available();
int c;
while ((c = msg.read())!= -1) {
char x = (char) c;
if (x=='1' || x=='0') break;
}
int currentPos = msg.available() + 1; //you need to unread the 1st 0 or 1
System.out.println("Position = "+(totalBytes-currentPos));https://stackoverflow.com/questions/18285522
复制相似问题