在jdk1.8以前,获取文件Base64字符串需要用到第三方库,从1.8开始,Java中引入了Base64相关的类
以下是代码示例
获取文件的Base64编码字符串
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Base64; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class Base64Encoder { private static final Logger LOGGER = Logger.getLogger("Base64Encoder"); public static void main(String[] args) { System.out.print("Enter an input filename: "); Scanner inputFromConsole = new Scanner(System.in); String filename = inputFromConsole.nextLine(); FileOutputStream outputToFile = null; try (FileInputStream inputFromFile = new FileInputStream(filename)) { System.out.print("Enter an encoded filename: "); filename = inputFromConsole.nextLine(); outputToFile = new FileOutputStream(filename); byte[] src = new byte[inputFromFile.available()]; inputFromFile.read(src); byte[] encodedBytes = Base64.getEncoder().encode(src); outputToFile.write(encodedBytes); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { if (outputToFile != null) { try { outputToFile.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } } }
解码Base64字符串还原文件
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import static java.lang.System.out; import java.util.Base64; import java.util.logging.Level; import java.util.logging.Logger; public class Base64Decoder { private static final Logger LOGGER = Logger.getLogger("Base64Decoder"); public static void main(String[] args) { if (args.length == 2) { try (FileInputStream encoded = new FileInputStream(args[0]); FileOutputStream decoded = new FileOutputStream(args[1])) { byte[] buffer = new byte[encoded.available()]; encoded.read(buffer); Base64.Decoder base64Decoder = Base64.getMimeDecoder(); decoded.write(base64Decoder.decode(buffer)); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } else { out.println("usage: java Base64Decoder <encoded filename> <decoded filename>"); out.println("for example: java Base64Decoder MyPic.jpg.txt MyPic.jpg"); } } }