0

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?

Reyno
  • 6,119
  • 18
  • 27
codingenious
  • 8,385
  • 12
  • 60
  • 90
  • Note that [`InputStream.read(bytes)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html#read(byte%5B%5D)) is not guaranteed to read all the bytes in the file. It may only read part of the file. You need to use [another method](https://stackoverflow.com/questions/858980/file-to-byte-in-java) to be sure that the whole file is read. – Jesper Jul 20 '21 at 07:03
  • Also, a `String` in Java is not a suitable container for arbitrary binary data. When you do `new String(bytes)` then the constructor of `String` will try to interpret the bytes as if they are encoded text (using your default character encoding), which can lead to errors. – Jesper Jul 20 '21 at 07:06
  • Did you have a look at `String.getBytes(Charset)`? Don't use the versions without a charset not even the constructor that only takes a `byte[]` but use `String(byte[], Charset)` instead. Otherwise you depend on the system's default charset which might not match. – Thomas Jul 20 '21 at 07:06
  • [Javascript is not Java](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – Reyno Jul 20 '21 at 07:11

1 Answers1

0

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")

LitVitNik
  • 29
  • 5
  • Don't use `getBytes()` but `getBytes(Charset)`. Otherwise you might use the wrong charset because your system has a default that differs from your expections. – Thomas Jul 20 '21 at 07:07