import sun.misc.BASE64Encoder;import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;public class Base64Util {/*** 文件转化成base64字符串*/public static String fileToBase64(String path) {String base64 = null;InputStream in = null;byte[] data = null;try {in = new FileInputStream(new File(path));data = new byte[in.available()];in.read(data);in.close();System.out.println(base64);} catch (Exception e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}//对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();//返回Base64编码过的字节数组字符串return encoder.encode(data);}/*** 将base64转换为文件并存储到指定位置*/public static boolean base64ToFile(String base64Str, String filePath) {if (base64Str == null && filePath == null) {return false;}try {Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64Str), StandardOpenOption.CREATE);} catch (IOException e) {e.printStackTrace();}return true;}}
@RequestMapping("/encode_file")@ResponseBodypublic String encodeFile() throws IOException {String path = "C:/Users/Administrator/Desktop/test/hello.txt";FileInputStream fi = new FileInputStream(new File(path));byte[] data = new byte[fi.available()];fi.read(data);fi.close();BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}@RequestMapping("/decode_file")@ResponseBodypublic String decodeFile() throws IOException {String code = "SEVMTE8gV09STEQ=";BASE64Decoder decoder = new BASE64Decoder();byte[] b = decoder.decodeBuffer(code);String str = new String(b,"utf-8");return str;}