看到楼主发的题目。刚好想练习下下IO流。根据题目的加密和解密规则,写了一个IO版的。供楼主参考。我也是新人代码写得比较粗糙。。。。。嘿嘿
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TestCipher {
public static void main(String[] args) {
File file = new File("file.txt");
File cipher = encrypt(file);
decode(cipher);
}
//加密
public static File encrypt(File file){
File cipher = null;
try{
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
cipher = new File("Cipher.txt");
FileOutputStream fos = new FileOutputStream(cipher);
BufferedOutputStream bos = new BufferedOutputStream(fos);
Scanner input = new Scanner(bis);
PrintWriter pWriter = new PrintWriter(bos);
pWriter.write("密文: ");
//加密算法
int i = 0;
while(input.hasNext()){
int t;
i = input.nextInt();
while(i != 0){
t = i % 10;
t = t + 5;
t = t % 10;
i /= 10;
pWriter.write(t+""); //要以字符串的形式写入文本文件.如果以int型写入,打开txt文件显示乱码。int型是以二进制数据存储
}
}
//关各种流。。。。
fis.close();
fos.close();
bis.close();
bos.close();
input.close();
pWriter.close();
}catch(IOException e){
e.printStackTrace();
}
return cipher; //返回加密后的文件对象
}
//解码
public static void decode(File cipher){
FileInputStream fis = null;
FileOutputStream fos = null;
Scanner input = null;
PrintWriter pWriter = null;
try{
fis = new FileInputStream(cipher);
fos = new FileOutputStream(new File("plaintext.txt"));
input = new Scanner(fis);
pWriter = new PrintWriter(fos);
pWriter.write("明文: ");
input.next(); //空读一行 跳过字符串"密文"
// 解码算法
int i = 0;
while(input.hasNext()){
int t;
i = input.nextInt();
while( i != 0){
t = i % 10;
if(i > 4){
t -=5;
System.out.print(t);
pWriter.write(t+"");
i /= 10;
}
else{
t += 5;
System.out.print(t);
pWriter.write(t+"");
i /= 10;
}
}
}
pWriter.close();
input.close();
fis.close();
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
|