Java基础-练习:文件加密解密
import java.io.*;
public class EncryptTest {
public static void main(String[] args) {
String path1 = "D:\\Java\\Test\\file1.txt";
String path2 = "D:\\Java\\Test\\file2.txt";
String path3 = "D:\\Java\\Test\\file3.txt";
// 把一个文件加密到一个文件
addPassword(path1, path2);
// 从一个文件解密到另一个文件
subPassword(path2, path3);
}
private static void addPassword(String path1, String path2) {
// 准备
// 声明
FileReader dis = null;
DataOutputStream dos = null;
// 创建
try {
dis = new FileReader(path1);
dos = new DataOutputStream(new FileOutputStream(path2));
// 读取
int i = dis.read();
// 加密
while (i != -1) {
dos.writeInt(i + 2);
i = dis.read();
}
// 刷新
dos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("1");
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void subPassword(String path2, String path3) {
// 准备
// 声明
DataInputStream dis = null;
FileWriter dos = null;
// 创建
try {
dis = new DataInputStream(new FileInputStream(path2));
dos = new FileWriter(path3);
// 读取
int i = dis.readInt();
// 加密
while (i != -1) {
System.out.print((char) (i - 2));
dos.write(i - 2);
i = dis.readInt();
}
// 刷新
dos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}