如何使我的加密/解密文件互相读取?

时间:2018-10-21 21:27:28

标签: java encryption

我会尽量做到这一点,不要感到困惑,但是我很困惑,所以会很棘手。

我已经制作了一个“一次性”加密程序(增加或减少字符)。现在,当我从与我的程序相同的文件夹中输入一个随机文件进行加密或解密时,该程序便会这样做。新加密/解密的文件将被正确发送到“加密”或“解密”文件。

我的问题是,当我尝试从最近的“解密”文件中提取并对其进行加密以将其恢复为正常状态(反之亦然)时,我什么也没得到。我已经发送到其中一个文件夹的数据都消失了,我不确定为什么。抱歉,这没有任何意义。

代码:

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

public class Encryptor
{
public static void main (String[] args)
{
  Scanner in = new Scanner(System.in);
  PrintWriter fileOutE;//Content going to "Encrypted" file
  PrintWriter fileOutD;//Content goint to "Decrypted" file

  String fileName = "";//Name of file user wants to encrypt/decrypt
  String encryptOrDecrypt = "";//eOrc stands for "Encrypt or Decrypt"
  String line = "";
  char ch = ' ';

  try
  {
     //Ask user for file to be encrypted or decrypted
     System.out.println("Please enter the name of the file: ");
     fileName = in.nextLine();

     //Ask user if they want to encrypt or decrypt file
     System.out.println("Would you like to encrypt or decrypt?: ");
     encryptOrDecrypt = in.nextLine();

     File f = new File (fileName);
     Scanner fileIn = new Scanner (f);
     fileOutE = new PrintWriter ("Encrypted.txt");//File for encrypted text
     fileOutD = new PrintWriter ("Decrypted.txt");//File for decrypted text

     if(encryptOrDecrypt.equalsIgnoreCase("encrypt"))
     {
        while(fileIn.hasNextLine())
        {
           line = fileIn.nextLine();

           for(int i = 0; i < line.length(); i++)
           {
              ch = line.charAt(i);

              if(Character.isLetter(ch))
              {
                 ch++;
              }

              fileOutE.print(ch);
           }

        }

           fileOutE.close();
           System.out.println("File has been sent to Encrypted.txt");
     }
     if(encryptOrDecrypt.equalsIgnoreCase("decrypt"))
     {
        while(fileIn.hasNextLine())
        {
           line = fileIn.nextLine();

           for(int i = 0; i < line.length(); i++)
           {
              ch = line.charAt(i);

              if(Character.isLetter(ch))
              {
                 ch--;
              }

              fileOutD.print(ch);
           }
        }

           fileOutD.close();
           System.out.println("File has been sent to Decrypted.txt");
     }  
   }//end try
   catch(Exception e)
   {
     System.out.println("Got an error");
   }//end catch

}//end main


}//end class

0 个答案:

没有答案