maven引入依赖:
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
</dependencies>
代码:
package code;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
public class Base64Test {
/**
* 从文件里读取编码后的信息
*/
@Test
public void decode() {
try {
File file = new File("d:/xhm.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String info = br.readLine();
info = info.replace("xxx", "");
// BASE64解密
byte[] d2 = info.getBytes();
byte[] bytes = Base64.decodeBase64(d2);
getFileByBytes(bytes,"d:/","3.7z");
System.out.println("over");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将文件加密
*/
public void encode() {
try {
File file = new File("");
// BASE64加密
byte[] data = Base64.encodeBase64(this.getBytesByFile("d:/xhm.7z"));
System.out.println("BASE64加密:" + new String(data));
} catch (Exception e) {
System.out.println("BASE64加解密异常");
e.printStackTrace();
}
}
//将文件转换成Byte数组
public byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//将Byte数组转换成文件
public static void getFileByBytes(byte[] bytes, 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 + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}