I have a String
which (I think) is the base64 representation of a series of bytes. I am trying to obtain the bytes using org.apache.commons.codec.binary.Base64InputStream
. However, apparently this stream has only one byte available.
The string was generated using a Base64OutputStream
and the original byte array was 398 bytes long.
I don't really know much about what I'm doing, but I think the Base64InputStream
should have 398 bytes available, shouldn't it? What am I doing wrong?
String myString = "rO0ABXNyABRqY..."; // Actual string is longer
ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(myString.getBytes(StandardCharsets.UTF_8));
Base64InputStream base64IS = new Base64InputStream(byteArrayIS);
System.out.println("String length : " + myString.length());
System.out.println("Available bytes in byteArrayInputStream: " + byteArrayIS.available());
System.out.println("Available bytes in base64InputStream: " + base64IS.available());
Output:
String length : 398
Available bytes in byteArrayInputStream: 398
Available bytes in base64InputStream: 1
The method Base64InputStream#available()
returns either 0 when the stream has reached its end, or 1 otherwise (see JavaDoc for details) - in other words it doesn't return the amount of data in the stream. You should call read()
on the stream until the available()
returns 0, and count the number of returned bytes to get the correct view on the stream's length.
You could also you use the following expression instead, and avoid dealing with the streams altogether:
byte[] result = org.apache.commons.codec.binary.Base64.decodeBase64(myString);