简体   繁体   English

Java-从InputStream读取字节数组,直到某个字符为止

[英]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.Base64InputStreamBufferedReaderJavaDoc )来包装InputStream如下所示:

try(BufferedReader reader = new BufferedReader(new InputStreamReader(new Base64InputStream(is)))) {
    String response = reader.readLine();
    ...
}

Notes: 笔记:

  • Try with resources will automatically close the reader when you're done. 完成后,尝试使用资源将自动关闭阅读器。
  • The Base64InputStream will decode Base64 encoded characters on the fly Base64InputStream将动态解码Base64编码的字符
  • 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视为行分隔符,以便确定行的结尾。
  • I am sure other libraries exist that will facilitate the on-the-fly decoding, or you could write a simple InputStreamWrapper yourself. 我确定存在其他有助于即时解码的库,或者您可以自己编写一个简单的InputStreamWrapper。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM