0
点赞
收藏
分享

微信扫一扫

Java8 Base64 和文件互转


import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class AnswerApp {

public static void main(String[] args) throws Exception {
String srcPath = "/home/jaemon/src/aal.jpg";
String descPath = "/home/jaemon/desc";

File srcFile = new File(srcPath);

// 读取文件的字节数组
byte[] bytes = FileUtils.readFileToByteArray(srcFile);
// 将文件字节数组 转 hexstring(16进制字符串)
String hexString = StringUtils.toHexString(bytes, bytes.length);


// 16进制 字符串 转 输入流
InputStream inputStream = hexToInputStream(hexString);
// 输入流 转 文件
FileUtils.copyInputStreamToFile(inputStream, new File(descPath + File.separator + "hex.jpg"));


// 文件 转 Base64
String base64String = Base64.getEncoder().encodeToString(bytes);

// Base64 转 文件
byte[] data = Base64.getDecoder().decode(base64String);
FileUtils.writeByteArrayToFile(new File(descPath + File.separator + "base64.jpg"), data);
// Files.write(Paths.get(descPath), data, StandardOpenOption.CREATE);
}



// 16 进制字符串转 输入流
private static InputStream hexToInputStream(String hexString) {
byte[] bytes = hexStringToBytes(hexString);
Assert.notNull(bytes, "bytes is null.");
return new ByteArrayInputStream(bytes);
}

// 16 进制字符串转 字节数组
private static byte[] hexStringToBytes(String hexString) {
if (org.springframework.util.StringUtils.isEmpty(hexString)) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}

private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}

​​Base64Utils 源码​​


举报

相关推荐

0 条评论