所以我把它作为我的主程序,我也有一个util程序。
当我使用应该加密的程序时,文本文件只会重命名它,而我认为它不会加密我的文件内容。
当我测试它时,它将重命名文件并打印出新的上下文,但是当我在参数中使用decode时它不会解密新消息;我是否因加密而导致解密失败?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class Prog4 {
public static void main(String[] args){
if (args.length != 3){
System.out.println("Enter the right amount of arguments!");
System.exit(0);
}
String command=args[0];
String key= args[1];
String fileName = args[2];
File file = new File(args[2]);
String fileExtention="";
if(args[0].equals("encode")){
fileExtention=".crypt";
}
else if (args[0].equals("decode")){
fileExtention=".decrypt";
}
else{
System.out.println("Enter decode or encode!");
Syst`enter code here`em.exit(0);
}
File newName = new File(fileName.substring(0,args[2].lastIndexOf("."))+fileExtention);
try{
Scanner sc= new Scanner(file);
PrintWriter out = new PrintWriter(newName);
if(args[0].equals("encode")){
while (sc.hasNextLine()){
Util4.encrypt(sc, out, key);
}
}
else if (args[0].equals("decode")){
while (sc.hasNextLine()){
Util4.decrypt(sc, out, key);
}
}
while (sc.hasNextLine()){
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
这是我的util类:
import java.io.PrintWriter;
import java.util.Scanner;
public class Util4 {
public static final int NUM_LETTERS = 26;
public static void encrypt(Scanner sc, PrintWriter out, String key){
while(sc.hasNext()){
char c;
int k;
String temporary="";
String line = sc.nextLine();
for (int i= 0; i< line.length(); ++i){
temporary += shiftUpByK(c= line.charAt(i),k=key.charAt(i%key.length())-'a');
}
System.out.println(temporary);
temporary="";
}
}
public static void decrypt(Scanner sc, PrintWriter out, String key){
while(sc.hasNext()){
char c;
int k;
String temporary="";
String line = sc.nextLine();
for(int i = 0; i < line.length(); ++i){
temporary += shiftDownByK(c=line.charAt(i), k=key.charAt(i%key.length())-'a');
}
System.out.println(temporary);
System.out.flush();
temporary="";
}
}
// shifting up for the encoding process
public static char shiftUpByK(char c, int k) {
if ('a' <= c && c <= 'z')
return (char) ('a' + (c-'a' + k) % NUM_LETTERS);
if ('A' <= c && c <= 'Z')
return (char) ('A' + (c-'A' +k) % NUM_LETTERS);
return c; // don't encrypt if not an alphabetic character
}
// shifting down for the decoding process
public static char shiftDownByK(char c, int k) {
return shiftUpByK(c, NUM_LETTERS-k);
}
}
答案 0 :(得分:0)
有两个问题:
Util4.encrypt()
和Util4.decrypt()
收到PrintWriter
但是,参数out
永远不会被写入out
。输出是
而是仅写入System.out
。所以你会看到
终端输出,但不会写入实际输出文件。要解决此问题,只需将System.out.println(temporary);
的两个实例更改为
out.println(temporary);
PrintWriter
未被关闭。在Prog4.java
添加一行:
out.close();
遵循现有的sc.close()
。或者,在out.flush()
每次写入后添加Util4.java
。