import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* @Description Base64工具处理类
* @Author WangKun
* @Date 2023/10/9 15:37
* @Version
*/
@Slf4j
public class Base64Utils {
final static String[] VIDEO_ARRAY = {".avi", ".wmv", ".mpg", ".mpeg", ".mov", ".rm", ".ram", ".swf", ".flv", ".mp4", ".3gp"};
final static String[] PICTURE_ARRAY = {".png", ".gif", ".jpg", ".jpeg"};
/**
* @param str
* @Description 字符串转Base64
* @Throws
* @Return java.lang.String
* @Date 2023-10-09 17:35:02
* @Author WangKun
*/
public static String strToBase64(String str) {
return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
}
/**
* @param base64Str
* @Description Base64转字符串
* @Throws
* @Return java.lang.String
* @Date 2023-10-09 17:37:43
* @Author WangKun
*/
public static String base64ToStr(String base64Str) {
return new String(Base64.getDecoder().decode(base64Str));
}
/**
* @param filePath
* @Description 文件转Base64编码(带文件后缀 ” 1.txt “)
* @Throws
* @Return java.lang.String
* @Date 2023-10-09 16:16:07
* @Author WangKun
*/
public static String fileToBase64(String filePath) {
try {
InputStream inputStream = FileUtils.openInputStream(new File(filePath));
return new String(Base64.getEncoder().encode(IOUtils.toByteArray(inputStream)), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("文件转Base64{} 异常", e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/**
* @param base64Str
* @param filePath
* @Description Base64编码转文件(带文件后缀 ” 1.txt “)
* @Throws
* @Return void
* @Date 2023-10-09 16:43:00
* @Author WangKun
*/
public static void base64ToFile(String base64Str, String filePath) {
try {
InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(base64Str.getBytes(StandardCharsets.UTF_8)));
FileOutputStream fos = new FileOutputStream(filePath);
byte[] bytes = new byte[is.available()];
int x = -1;
while ((x = is.read(bytes)) != -1) {
fos.write(bytes);
}
is.close();
fos.close();
} catch (IOException e) {
log.error("Base64转文件{} 异常", e.getMessage(), e);
e.printStackTrace();
}
}
}
07-14
6326
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-27
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交