结果效果贴图:
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();
}
}