请耐心等待,因为我是该网站的新手。下面是我为我的 Java 类编程编写的一个程序,虽然到目前为止大部分都运行良好,但我似乎无法摆脱一个特定的错误。
当程序到达第三个 if 块(选择 == 3)时,它不会让用户输入任何数据,如果该行
“输出流 = openOutputTextFile(newerFileName);”
存在于 if 块中,则发生 FileNotFoundException。在修改了我的代码一段时间后,我发现错误正在被抛出,因为程序无法再找到 inputStream。虽然我检查并发现程序仍然可以找到、读取和写入引发错误的文件。
我在想,由于该错误仅在我将 outputStream 放入并被 inputStream 抛出时才发生,因此它可能与文件流有关。我只是不知道具体是什么
有人对我如何解决这个问题有任何想法吗?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}