文件阅读器并将其实现为密码

时间:2016-02-29 05:11:23

标签: java encryption caesar-cipher

我是Java的新手,有点了解它,并且正在为我的CS类中的Caesar Cipher编写一些代码。我能够从文件中读取一行代码,它可以decryptencrypt就好了,但我认为我的老师想要一个完整的文档能够加密或解密。我知道有可能让它读取整个文档并将其存储到字符串中,但我该如何去做?

感谢您的帮助!如果您需要参考我的其他课程,请告诉我。

    import java.util.Scanner;
    import java.io.*;

    public class Project3 {

    public static void main(String[] args) {
        Cipher caesar = new Cipher();
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a filename to encode or decode.");
        String f = input.nextLine();
        String fileName = f;
        String line = null;
        System.out.println("Enter the number of steps to encode or decode the file by: ");
            int i = input.nextInt();
            input.nextLine();
        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            while((line = bufferedReader.readLine()) != null){
                System.out.println(line);
                System.out.println("What would you like to do? Enter [e] to encrypt or press [d] to decrypt.");
                String a = input.nextLine();
                    if(a.equals("e")){
                        String encoded = caesar.useCipher(line,i);
                        caesar.writeToFile(encoded);
                        break;
                        }
                    if(a.equals("d")){
                        String decoded = caesar.useCipher(line,(-i));
                        caesar.writeToFile(decoded);
                        break;
                        }
            }            
        }
        catch(FileNotFoundException ex){
            System.out.println("Unable to open file '" + fileName + "'");                
        }
        catch(IOException ex){
            System.out.println("Error reading file '" + fileName + "'");                  
          }
      }    
}

1 个答案:

答案 0 :(得分:0)

您的代码已经有循环来处理整个文件。

唯一的问题是提示询问用户想要做什么。该部分属于while循环之前(之前)。