[英]Java - read an array of bytes from an InputStream until a certain character
i need to read an Base64 encoded array of bytes from an inputstream. 我需要从输入流中读取Base64编码的字节数组。
I have to stop reading when I reach a \\n character in the decoded string, i cannot find an efficient way to do this. 当我在解码的字符串中到达\\ n字符时,我必须停止阅读,我找不到有效的方法来执行此操作。
Now i ended with something like this but it does not work as intended because it's too easy it catches an exception and messes all up... 现在我结束了这样的事情,但是它并没有按预期工作,因为它太容易了,它捕获了异常并弄乱了一切……
byte buffer[] = new byte[2048];
byte results[] = new byte[2048];
String totalResult = null;
try {
int bytes_read = is.read(buffer);
while (buffer[bytes_read - 1] != '\n') {
bytes_read = is.read(buffer);
String app = new String(buffer, 0, bytes_read);
totalResult += app;
}
String response = Base64.getDecoder().decode(totalResult).toString();
Any idea? 任何想法? The input Stream does not close, so i need to get data from it and separated by '\\n'
输入Stream不会关闭,因此我需要从中获取数据并以'\\ n'分隔
Rather than reinventing the wheel, consider using (for example) org.apache.commons.codec.binary.Base64InputStream
from the Commons Codec project and a BufferedReader
( JavaDoc ) to wrap your InputStream
like so: 与其重新发明轮子,不如考虑使用(例如)来自Commons Codec项目的
org.apache.commons.codec.binary.Base64InputStream
和BufferedReader
( JavaDoc )来包装InputStream
如下所示:
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new Base64InputStream(is)))) {
String response = reader.readLine();
...
}
Notes: 笔记:
BufferedReader.readLine()
considers \\n
, \\r
or \\r\\n
to be line separators for the purpose of determining the end of a line. BufferedReader.readLine()
将\\n
, \\r
或\\r\\n
视为行分隔符,以便确定行的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.