Java - encode a string to Base64 - java

I am converting a piece of javascript code to java and want to encode a string to Base64 in java.
Code in javascript:
let encodedData = btoa(String.fromCharCode.apply(null, new Uint8Array(array)))
This converts Uint8Array to string first and then encode it to Base64. But I am not able to find a way to do same in java.
Java code is
InputStream insputStream = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
insputStream.read(bytes);
insputStream.close();
byte[] encodedBytes = Base64.getEncoder().encode(bytes);
Which is encoding bytes. Dues to which, encodedData(js) and encodedBytes(java) are not same.
What I want to do is something like:
String str = new String(bytes);
byte[] encodedBytes = Base64.getEncoder().encode(str); // ERROR: encode doesn't accept string
Is there any way to achieve this?

Base64.getEncoder().encode(str.getBytes(Charset)) may help you
(as Thomas noticed). But i can't guess your charset. The right syntax for Charset will be something like StandartCharsets.SOME_CHARSET or Charset.forName("some_charset")

Related

Convert InputStream to base64 and then to byte array

I need a byte array, but the requirement is like first I need to convert the input stream to base64 and then the base64 to byte array.
I have tried directly to the byte array, but the requirement is like need to convert the InputStream to base64 and then byte[].
InputStream input = ....
byte[] byteArray = IOUtils.toByteArray(input);
You can use Base64 from java.util package to encode your stream to base 64
Something like this:
String initialString = "original text";
InputStream input = new ByteArrayInputStream(initialString.getBytes());
byte[] byteEncoded = Base64.getEncoder().encode(IOUtils.toByteArray(input));
The method is Base64.getEncoder().encode and have 3 candidates:
public byte[] encode(byte[] src
public int encode(byte[] src,byte[] dst)
public ByteBuffer encode(ByteBuffer buffer)
Hoping that help

convert UTF-8 String to ISO-8859-1 java

I have an application where i want to convert an utf-8 encoded string to ISO-8859-1 because this is the encoding of my oracle DB.
Currently this is what i'm inserting in my db:
België
But i expect this:
België
When i print my string in java i get the following:
België
Can anybody help me?
This is what i already tried:
System.out.println(xmlString);
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");
ByteBuffer inputBuffer = ByteBuffer.wrap(xmlString.getBytes(utf8charset));
// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);
// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();
xmlt = new oracle.xdb.XMLType(con, new String(outputData, iso88591charset));
suggestion from the comments didn't work either:
byte[] utf8 = xmlString.getBytes("UTF-8");
byte[] latin = new String(utf8, "UTF-8").getBytes("ISO-8859-1");
ByteArrayInputStream bis = new ByteArrayInputStream(latin);
xmlt = new oracle.xdb.XMLType(con, bis);
Normally UTF-8 can do encoding of any Unicode code. ISO-8859-1 is capable of handling tiny fraction of them and transcoding of UTF-8 to ISO-8859-1 can cause "replacement characters" (�) to appear in your text when unsupported characters are found and also there might be other issues.
Transcoding from ISO-8859-1 to UTF-8 dont have any problem.
I would suggest to transcode text:
byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");
or
byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");

How to convert a byte string to String? [duplicate]

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

How to convert byte array to base64 String

List<Map<String, Object>> lists = baseDao.getJdbcTemplate().queryForList(queryForImages, productId);
**System.out.println("size----" + lists.size());**
ArrayList<String> arrayList = new ArrayList<String>();
for (Map<String, Object> base64 : lists) {
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
// byte[] encodedImage = Base64.encodeBase64(imgData);
System.out.println("encoded---2" + base64Encoded);
}
i retrieve list of images from db and convert byte array to base64 string ,if i sysout only the last image in the list prints in sysout , even sysout list.size under the method is not printing .
In android, you can use Base64 (android.util.Base64) to encoded byte[] to String;
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
and
Decoding part as like following;
byte[] byteArray = org.apache.commons.codec.binary.Base64.decodeBase64(encodedString);
Usually this technique used in android app to send binary file/data to Server, using Web Service;
To start with, this is wrong:
String base64Encoded = new String(imgData, StandardCharsets.UTF_8);
The image bytes you have do not represent UTF-8 encoded text, so it makes no sense to create a String out of the bytes, pretending that this is UTF-8 encoded text.
If you are using Java 8, then use the Base64 class available in the standard library:
import java.util.Base64;
// ...
byte[] imgData = (byte[]) base64.get("images");
String base64Encoded = Base64.getEncoder().encodeToString(imgData);
If you are not using Java 8, you can use a third-party library, for example Apache Commons Codec, which includes classes for Base64 encoding and decoding.
If you are working with Android you can use the following code by importing the Android version of the Base64 class:
Base64.encodeToString(payload, Base64.DEFAULT);
From Android API 26, you can use java.util.Base64 as well.
Prior to java 1.8 use apache commons library
String base64 = new String(Base64.encodeBase64(imgData))

Decoding a Base64 string in Java

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.
The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.
This is the code I'm currently using:
Base64 decoder = new Base64();
byte[] decodedBytes = decoder.decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");
The following should work with the latest version of Apache common codec
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));
and for encoding
byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));
If you don't want to use apache, you can use Java8:
byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes) + "\n");
Commonly base64 it is used for images. if you like to decode an image (jpg in this example with org.apache.commons.codec.binary.Base64 package):
byte[] decoded = Base64.decodeBase64(imageJpgInBase64);
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\output\\image.jpg");
fos.write(decoded);
fos.close();

Categories