fourcal/src/main/java/cn/palmte/work/utils/Base64Utils.java

104 lines
2.7 KiB
Java
Raw Normal View History

2021-10-28 08:09:50 +00:00
package cn.palmte.work.utils;
import top.jfunc.common.crypto.symmetric.Base64;
import java.io.*;
/**
* BASE64
* javabase64-1.3.1.jar
*
* @version 1.0
*/
public class Base64Utils {
/**
*
*/
private static final int CACHE_SIZE = 1024;
/**
* BASE64
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/**
* BASE64
*/
public static String encode(byte[] bytes) throws Exception {
return Base64.encode(bytes);
}
/**
* BASE64
*
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
* BASE64
* @param filePath
* @param base64
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
*
*
* @param filePath
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
2021-12-06 06:49:29 +00:00
try( FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048)) {
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
data = out.toByteArray();
2021-10-28 08:09:50 +00:00
}
}
return data;
}
/**
*
*
* @param bytes
* @param filePath
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
2021-12-06 06:49:29 +00:00
try(InputStream in = new ByteArrayInputStream(bytes);
OutputStream out = new FileOutputStream(destFile)){
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
2021-10-28 08:09:50 +00:00
}
}
}