读取 inputStream 的一部分并转换为字节列表
Reading a part of an inputStream and converting to list of bytes
我正在尝试实施一种方法,该方法从 txt 文件中接收 InputStream,该文件具有用引号引起来的特定字符串。然后应将字符串作为字节列表返回。
public static List<Byte> getQuoted(InputStream in) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
boolean quoteWasFound = false;
int r;
// First go through the input stream until reaching first quotation mark.
while ((r = reader.read()) != -1) {
in.readNBytes(2);
if ((char) r == '"') {
quoteWasFound = true;
break;
}
}
List<Byte> byteList = new ArrayList<>();
// If quote mark was found in previous loop, start adding the bytes from the
// inputstream (2 at a time) until one of two thing happen: another quotation
// mark was found OR reached end of input stream.
while (quoteWasFound && (r = reader.read()) != -1) {
if ((char) r == '"')
break;
for (int i = 0; i <= 1; i++) {
byteList.add((byte) in.read());
}
}
if (byteList.isEmpty())
return null;
else
return byteList;
} catch (IOException e) {
throw new IOException();
}
}
当我 运行 代码时,我得到了这个输出:
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
这就是我所期待的:
[114, 101, 116, 117, 114, 110, 32, 116, 104, 105, 115, 32, 115, 117, 98, 115, 116, 114, 105, 110, 103]
我猜我从 int 到 char 或从 int 到 byte 的转换方式有问题,但我不知道是什么原因造成的。
提前感谢所有分享他们智慧的人!
在同一流中混合 Reader 和输入流是导致问题的原因。您必须选择其中之一,而不是两者都选择。
我正在尝试实施一种方法,该方法从 txt 文件中接收 InputStream,该文件具有用引号引起来的特定字符串。然后应将字符串作为字节列表返回。
public static List<Byte> getQuoted(InputStream in) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
boolean quoteWasFound = false;
int r;
// First go through the input stream until reaching first quotation mark.
while ((r = reader.read()) != -1) {
in.readNBytes(2);
if ((char) r == '"') {
quoteWasFound = true;
break;
}
}
List<Byte> byteList = new ArrayList<>();
// If quote mark was found in previous loop, start adding the bytes from the
// inputstream (2 at a time) until one of two thing happen: another quotation
// mark was found OR reached end of input stream.
while (quoteWasFound && (r = reader.read()) != -1) {
if ((char) r == '"')
break;
for (int i = 0; i <= 1; i++) {
byteList.add((byte) in.read());
}
}
if (byteList.isEmpty())
return null;
else
return byteList;
} catch (IOException e) {
throw new IOException();
}
}
当我 运行 代码时,我得到了这个输出:
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
这就是我所期待的:
[114, 101, 116, 117, 114, 110, 32, 116, 104, 105, 115, 32, 115, 117, 98, 115, 116, 114, 105, 110, 103]
我猜我从 int 到 char 或从 int 到 byte 的转换方式有问题,但我不知道是什么原因造成的。
提前感谢所有分享他们智慧的人!
在同一流中混合 Reader 和输入流是导致问题的原因。您必须选择其中之一,而不是两者都选择。