我正在尝试通过向上加密一个字母并在解密时向下一个字母来加密和解密文件。但是,每次我运行该程序时,无论输入什么文件,都会提示我“找不到文件”。我究竟做错了什么?任何帮助或建议将是巨大的。下面是我的代码:-
import java.io.File;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class Mission09
{
public static void main (String[]args)
{
Scanner in = new Scanner (System.in);
File f;
Scanner fileIn;
PrintWriter fileOut;
PrintWriter fileOutDecrypt;
String fileName = "";
String userAnswer = "";
String line = "";
try
{
//Get file name from the user
System.out.println ("Please enter the name of the file.");
fileName = in.nextLine ();
//Get user input for encryption or decryption
System.out.println ("Would you like to encrypt or decyrpt the file?");
userAnswer = in.nextLine ();
//Build the File and attach a Scanner to it
f = new File (fileName);
fileIn = new Scanner (f);
//Loop through the file
if (userAnswer.equalsIgnoreCase ("Encrypt"))
{
fileOut = new PrintWriter ("Encrypted.txt");
while (fileIn.hasNextLine ())
{
line = fileIn.nextLine ();
for (int i = 0; i < line.length (); i++)
{
Character c = ' ';
char ch = line.charAt (i);
if (c.isLetter (ch))
{
if (ch == 'z')
ch = 'a';
else
ch++;
}
fileOut.print(ch + " ");
}
}
}
if (userAnswer.equalsIgnoreCase ("Decrypt"))
{
fileOut = new PrintWriter ("Decrypted.txt");
while (fileIn.hasNextLine())
{
line = fileIn.nextLine();
for (int i = 0; i < line.length (); i--)
{
Character x = ' ';
char cha = line.charAt (i);
if (x.isLetter (cha))
{
if (cha == 'z')
cha = 'a';
else
cha--;
fileOut.print(cha + " ");
}
fileOut.close();
}
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Sorry that file cannot be found. Please enter another file.");
}
}
}
答案 0 :(得分:0)
输入文件的整个路径。它为我工作。
例如:C:\Users\xxxxxxxxxx\Desktop\test.txt
。
在fileOut.close()
加密条件的末尾还包含if
答案 1 :(得分:0)
请提供绝对路径和带有适当扩展名的完整文件名。 当然,问题出在您提供文件路径的方式上。
我尝试使用绝对路径,并且相同的代码对我来说很好用。
我的游戏围栏示例:C:\code\WprkSpacePlaypen\Temp\src\abhijeet.txt