简体   繁体   中英

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.

I have to stop reading when I reach a \\n character in the decoded string, i cannot find an efficient way to do this.

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'

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:

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
  • BufferedReader.readLine() considers \\n , \\r or \\r\\n to be line separators for the purpose of determining the end of a line.
  • I am sure other libraries exist that will facilitate the on-the-fly decoding, or you could write a simple InputStreamWrapper yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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