jdk8 Base64 基础操作

  • 编码

String base64encodedString = Base64.getEncoder().encodeToString(str.getBytes("utf-8"))

  • 解码

new String(Base64.getDecoder().decode(base64encodedString), "utf-8"))

  • URL编码

Base64.getUrlEncoder().encodeToString(url.getBytes("utf-8"))

  • URL解码

new String(Base64.getUrlDecoder().decode(base64encodedString), "utf-8"))

  • MIME编码

Base64.getMimeEncoder().encodeToString(bytes)

  • MIME解码

Base64.getMimeDecoder().decode(str)

文件Base64加密

  • URL文件

 public static String url2Base64(String urlStr) {
        InputStream in;
        String base64Str;
        try {
            // 获取url连接
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            // 获取URL的InputStream流
            in = conn.getInputStream();
            byte[] buffer = new byte[in.available()];
            in.read(buff);
            // Base64编码
            base64Str = Base64.getEncoder().encodeToString(buffer);

            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base64Str;
    }
  • File加密

public static String file2Base64(File file) {
        if(file == null) {
            return "";
        }
        InputStream in;
        String base64Str;
        try {
            in = new FileInputStream(file);
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            // Base64编码
            base64Str = Base64.getEncoder().encodeToString(buffer);
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return base64Str;
    }

文件Base64解密

  • 转InputStream

public static InputStream base64ToInputStream(String base64) {

        byte[] buff = Base64.getDecoder().decode(base64);

        return new ByteArrayInputStream(buff);
    }
  • 转File

public static File base64ToFile(String base64, String path) {
        byte[] buff = Base64.getDecoder().decode(base64);
        File file = null;
        FileOutputStream fout = null;
        try {
            file = new File(path);
            fout = new FileOutputStream(file);
            fout.write(buff);
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

你可能感兴趣的:(java,java)