结果效果贴图:

package Jobday12_作业;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("输入目录:");
String s = new Scanner(System.in).nextLine();
File dir = new File(s);
if (!dir.isDirectory()) {
System.out.println("输入不是目录");
return;
}
encryption(dir);
if (dir.listFiles() != null) {
System.out.println("加密完毕!");
}
}
private static void encryption(File dir) {
// 目录列表
File[] files = dir.listFiles();
if (files == null) {
System.out.println("没有文件");
return;
}
for (File f : files) {
if (f.isFile()) {
try {
encrypt(f);
System.out.println(f.getName() + "加密成功");
} catch (IOException e) {
System.out.println("---" + f.getName() + "加密失败");
}
} else {
encryption(f);
}
}
return;
}
private static void encrypt(File f) throws IOException {
RandomAccessFile raf = new RandomAccessFile(f, "rw");
byte[] buff = new byte[8192];
int n;
int key = 123456789;
while ((n = raf.read(buff)) != -1) {
for (int i = 0; i < n; i++) {
buff[i] ^= key;
}
raf.seek(raf.getFilePointer() - n);
raf.write(buff, 0, n);
}
raf.close();
}
}
本文介绍了一个使用Java编写的递归文件加密程序。该程序通过用户指定的目录进行操作,能够遍历目录及其子目录下的所有文件并对其进行加密。加密过程利用了RandomAccessFile类来读取和写入文件内容,并采用简单的异或操作实现加密逻辑。

1万+

被折叠的 条评论
为什么被折叠?



