解密加密的文本文件

时间:2014-11-18 21:03:19

标签: java encryption

我有解密方法打开带有加密文本的测试文件,然后读取并解读我从输入文件读入的每行文本。文本文件名为mystery.txt。 我只能在输入单个字符时才能使用该方法,但是我无法在打开.txt文件并逐行解密的情况下使用它。

解密方法:

public static String cipherDecipherString(String text)

{
 // These are global. Put here for space saving
 private static final String crypt1 = "cipherabdfgjk";
 private static final String crypt2 = "lmnoqstuvwxyz";

    // declare variables
    int i, j;
    boolean found = false;
    String temp="" ; // empty String to hold converted text
    readFile();
    for (i = 0; i < text.length(); i++) // look at every chracter in text
    {
        found = false;
        if ((j = crypt1.indexOf(text.charAt(i))) > -1) // is char in crypt1?
        {           
            found = true; // yes!
            temp = temp + crypt2.charAt(j); // add the cipher character to temp
        }
        else if ((j = crypt2.indexOf(text.charAt(i))) > -1) // and so on
        {
            found = true;
            temp = temp + crypt1.charAt(j);
        }
        if (! found) // to deal with cases where char is NOT in crypt2 or 2
        {
            temp = temp + text.charAt(i); // just copy across the character
        }
    }
    return temp;
}

我的readFile方法:

public static void readFile()
{
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String InputFileName;
    String nextLine;
    clrscr();
    System.out.println("Please enter the name of the file that is to be READ (e.g. aFile.txt: ");
    InputFileName = Genio.getString();
    try
    {
        fileReader = new FileReader(InputFileName);
        bufferedReader = new BufferedReader(fileReader); 
        nextLine = bufferedReader.readLine();
        while (nextLine != null)
        {
            System.out.println(nextLine);
            nextLine = bufferedReader.readLine();
        }
    }
    catch (IOException e)
    {
        System.out.println("Sorry, there has been a problem opening or reading from the file");
    }
    finally
    {
        if (bufferedReader != null)
        {
            try
            {
                bufferedReader.close();    
            }
            catch (IOException e)
            {
                System.out.println("An error occurred when attempting to close the file");
            }
        }  
    }
}

现在我认为我只能调用我的readFile()方法,然后进入解密代码,然后让它在文件中工作,但我根本无法使用它。

1 个答案:

答案 0 :(得分:0)

在readFile()中,你没有对你读过的行做任何事情,你没有在任何地方调用cipherDecipherString()。

编辑:您可以将文件中的所有行添加到数组中,然后从函数中返回数组。然后迭代遍历该数组并逐行解密

将readFile()返回类型更改为ArrayList;

ArrayList<String> textLines = new ArrayList<>();
while(nextLine != null) {
    textLines.add(nextLine);
    nextLine = bufferedReader.readLine();
}

return textLines;

然后在cipherDecipherString()中调用readFile()。

ArrayList<String> textLines = readFile();