public String fileToBase64(String path) {
String base64 = null;
InputStream in = null;
try {
File file = new File(path);
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
if (!file.exists())
return "";
ByteArrayOutputStream encode = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
try {
in = new FileInputStream(file);
// 将内容读取内存中
int len = -1;
while ((len = in.read(buffer)) != -1) {
encode.write(buffer, 0, len);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
byte[] encode1 = Base64.getEncoder().encode(encode.toByteArray());
base64 = new String(encode1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
文件进行Base64编码
最新推荐文章于 2024-05-10 22:04:13 发布