首先要在project文件夹目录下建立三个text的文本命名,第一个文本写入字符,其余两个会在程序运行结束后写入到text的文本里,打开文本对比是否正确。
加密代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class HR {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
File file1=new File("file1.txt");
br=new BufferedReader(new FileReader(file1));
File file2=new File("file2.txt");
bw=new BufferedWriter(new FileWriter(file2));
String s="";
while((s=br.readLine())!=null) {
s=s.trim();
String str="";
for(int i=0;i<s.length();i++) {
char ch=s.charAt(i);
if(Character.isLetter(ch)) {
if(Character.isUpperCase(ch)) {
if(ch-'A'+1>25) {
ch=(char)('A'+(ch-'A'+1)%26);
}else {
ch=(char)(ch+1);
}
}
if(Character.isLowerCase(ch)) {
if(ch-'a'+1>25) {
ch=(char)('a'+(ch-'a'+1)%26);
}else {
ch=(char)(ch+1);
}
}
}
str=str+ch;
}
bw.write(str);
bw.newLine();
}
}
catch(Exception e) {
e.printStackTrace();
}finally{
try {
bw.close();
br.close();
}catch(Exception e) {
e.printStackTrace();
}
}
System.out.println("文件加密完成");
}
}
解密代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class HR {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
File file2=new File("file2.txt");
br=new BufferedReader(new FileReader(file2));
File file3=new File("file3.txt");
bw=new BufferedWriter(new FileWriter(file3));
String s="";
while((s=br.readLine())!=null) {
s=s.trim();
String str="";
for(int i=0;i<s.length();i++) {
char ch=s.charAt(i);
if(Character.isLetter(ch)) {
if(Character.isUpperCase(ch)) {
if(ch-'A'-1>25) {
ch=(char)('A'+(ch-'A'-1)%26);
}else {
ch=(char)(ch-1);
}
}
if(Character.isLowerCase(ch)) {
if(ch-'a'-1>25) {
ch=(char)('a'+(ch-'a'-1)%26);
}else {
ch=(char)(ch-1);
}
}
}
str=str+ch;
}
bw.write(str);
bw.newLine();
}
}
catch(Exception e) {
e.printStackTrace();
}finally{
try {
bw.close();
br.close();
}catch(Exception e) {
e.printStackTrace();
}
}
System.out.println("文件解密完成");
}
}
代码仅供参考