1. 文件转二进制
private static byte[] getFileByte(String imgUrl) throws Exception {
InputStream inStream = new FileInputStream(imgUrl);
ByteArrayOutputStream outStream = null;
try {
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return outStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.close();
}
}
return null;
}
2. 二进制转文件
public static void getFile(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && !dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
3. base64/数组转化
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public static void main(String[] args) throws Exception {
byte[] arr = getFileByte("D:\\DAY_WORK\\2022\\month_12\\worksheet-1190_1.png");
String basStt1 = Base64.getEncoder().encodeToString(arr);
String basStr = DatatypeConverter.printBase64Binary(arr);
System.out.println(basStt1);
byte[] newArr = DatatypeConverter.parseBase64Binary(basStr);
getFile(newArr, "D:\\DAY_WORK\\2022\\month_12", "yyy.png");
System.out.println(basStr);
}
4. 换包
import org.apache.commons.codec.binary.Base64;
public static void main(String[] args) throws Exception {
String basStr = ImageText.imgBase64Str;
// byte[] newArr = DatatypeConverter.parseBase64Binary(basStr);
byte[] newArr = handleGet(basStr);
getFile(newArr, "D:\\DAY_WORK\\2022\\month_12", "test_file_fully.png");
System.out.println(basStr);
}
private static byte[] handleGet(String base64Str) {
byte[] b = Base64.decodeBase64(base64Str);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
return b;
}
参考:
https://blog.csdn.net/u010629610/article/details/114896129