当前位置: 首页 > 工具软件 > Java Base64 > 使用案例 >

java 生成base64

韩夕
2023-12-01
/***
 * 指定文件生成base64编码内容
 * @param path
 * @return
 * @throws IOException
 */
public static String encodeBase64ByFilePath(String path) throws IOException{
   File file = new File(path);
   return encodeBase64ByFile(file);
}

public static String encodeBase64ByFile(File file) throws IOException{
   FileInputStream inputStream = new FileInputStream(file);
   byte[] buffer = new byte[(int)file.length()];
   inputStream.read(buffer);
   inputStream.close();
   Base64.Encoder encoder=Base64.getEncoder();
   return encoder.encodeToString(buffer);
}

传入文件要写入的内容,写入的文件

public void writeField(String path,String content) throws Exception{
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(path));
    BufferedWriter buff = new BufferedWriter(os);
    buff.write(content);
    buff.close();
}

调用:path1要转化文件路径,path2即base64编码的新文件路径

writeField(path2,encodeBase64ByFilePath(String path1))

 类似资料: