简体   繁体   English

Java - 将字符串编码为 Base64

[英]Java - encode a string to Base64

I am converting a piece of javascript code to java and want to encode a string to Base64 in java.我正在将一段 javascript 代码转换为 java,并希望在 java 中将字符串编码为 Base64。 Code in javascript: javascript中的代码:

let encodedData = btoa(String.fromCharCode.apply(null, new Uint8Array(array)))

This converts Uint8Array to string first and then encode it to Base64.这首先将 Uint8Array 转换为字符串,然后将其编码为 Base64。 But I am not able to find a way to do same in java.但是我无法找到一种在 Java 中执行相同操作的方法。 Java code is Java代码是

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.因此, encodedData (js) 和encodedBytes (java) 是不一样的。 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). Base64.getEncoder().encode(str.getBytes(Charset))可以帮助你(正如托马斯注意到的那样)。 But i can't guess your charset.但我猜不出你的字符集。 The right syntax for Charset will be something like StandartCharsets.SOME_CHARSET or Charset.forName("some_charset") Charset 的正确语法类似于StandartCharsets.SOME_CHARSETCharset.forName("some_charset")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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