加密:
[Java] 纯文本查看 复制代码 package hehe;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
/*
* 加密
*/
public class Jia_Mi {
public static void main(String[] args) throws IOException {
char[] arr = {'h','e','i','m','a'};
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
int n = 0;
int b;
LinkedList<Character> ll = new LinkedList<>();
while ((b = br.read()) != -1) {
ll.add((char)(b^arr[n++]));
n %= 5;
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
for (char c : ll) {
bw.write(c);
}
bw.close();
}
}
解密:
[Java] 纯文本查看 复制代码 package hehe;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.TreeMap;
/*
* 题目3:在d盘目录下有一个加密文件a.txt(文件里只有英文和数字),密码是“heima”,当密码输入正确时才能读取文件里的数据。现要求用代码来模拟读取文件的过程,并统计文件里各个字母出现的次数,并把统计结果按照“a:2个;b:3个;”的格式输出到d盘的count.txt中
*/
public class Jie_Mi {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String input = null;
do {
System.out.println( input == null ? "请输入秘钥:" : "输入错误!请重试:" );
input = sc.nextLine();
} while (!"heima".equals(input));
sc.close();
System.out.println("开始解密...");
char[] arr = input.toCharArray();
LinkedList<Character> ll = reader(arr);
TreeMap<Character, Integer> tm = new TreeMap<>();
for (char key : ll) {
tm.put(key, tm.containsKey(key) ? tm.get(key)+1 : 1 );
}
BufferedWriter bw = new BufferedWriter(new FileWriter("count.txt"));
for (char key : tm.keySet()) {
bw.write(key + ":" + tm.get(key) + "个; ");
}
bw.close();
System.out.println("解密统计完成请查收!");
}
public static LinkedList<Character> reader(char[] arr) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
int n = 0;
int b;
LinkedList<Character> list = new LinkedList<>();
while ((b = br.read()) != -1) {
list.add((char)(b^arr[n++]));
n %= 5;
}
br.close();
return list;
}
}
|