首页 > 其他分享 >JDK8的base64编解码、图片转base64

JDK8的base64编解码、图片转base64

时间:2022-09-29 08:56:26浏览次数:51  
标签:编解码 base64 java String Base64 JDK8 import out

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
* JDK8新特性
*
* @Description
* @Author quxiutao
* @CreateTime 2022-09-28 17:35
* @Remark
* @Version 1.0
**/
public class Base64Class {

public static void main(String[] args) throws Exception{

Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();

String text = "quxiutao";
byte [] bytes = text.getBytes(StandardCharsets.UTF_8);

//编码
String encoderText = encoder.encodeToString(bytes);
System.out.println(encoderText);

//解码
byte [] decoderByte = decoder.decode(encoderText);
System.out.println(new String(decoderByte, StandardCharsets.UTF_8));

//图片转base64
String path = "C:\\Users\\QuXiuTao\\Desktop\\";
String fileName = "123.png";
InputStream inputStream = new FileInputStream(path + fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte [] bytes1 = new byte[1024];
int length;
while ((length = inputStream.read(bytes1)) != -1) {
out.write(bytes1);
}
String base64Text = encoder.encodeToString(out.toByteArray());
System.out.println(base64Text);


}

}

标签:编解码,base64,java,String,Base64,JDK8,import,out
From: https://www.cnblogs.com/quxiutao/p/16740211.html

相关文章