Encode Decode Byte Array To Base64 String Using Java

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...

The code uses non standard classes found in the sun.misc package to convert to and from Base64. These classes may change in the future. Taken from Example Depot.

1
2
3
4
5
6
 // Convert a byte array to base64 string
byte[] buf = new byte[]{0x12, 0x23};
String s = new sun.misc.BASE64Encoder().encode(buf);
 
// Convert base64 string to a byte array
buf = new sun.misc.BASE64Decoder().decodeBuffer(s);

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Java: Convert Stream To Byte[]

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading ... Loading ...

Say you call an HTTP request that returns a byte array which contains a binary file, how would you do this? First things first. Access it using an HttpURLConnection object. Once you have connected to the URL, get the InputStream object and that is when you will be able to convert the stream into a byte array. Check the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
URL u = new URL("MY URL");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || contentLength == -1) {
    throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
    bytesRead = in.read(data, offset, data.length - offset);
    if (bytesRead == -1) break;
    offset += bytesRead;
}
in.close();

The data variable is the byte array. You can then do whatever you like (e.g. saving it as a binary file) after you have retrieved the byte array object.

Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.

Related Posts with Thumbnails