gpt4 book ai didi

java - 在 Java 中读取文件时 FileNotFoundException 捕获错误

转载 作者:行者123 更新时间:2023-11-29 06:39:03 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的程序,从文本文件中读取整数,然后将总和输出到输出文件。我得到的唯一错误是在第 38 行的 catch block 中“ Unresolved 编译问题:无法解析文件”。请注意,"file"是我的输入文件对象的名称。如果我注释掉这个异常 block ,程序运行正常。任何建议将不胜感激!

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

public class ReadWriteTextFileExample
{
public static void main(String[] args)
{
int num, sum = 0;

try
{
//Create a File object from input1.txt
File file = new File("input1.txt");
Scanner input = new Scanner(file);

while(input.hasNext())
{
//read one integer from input1.txt
num = input.nextInt();
sum += num;
}
input.close();

//create a text file object which you will write the output to
File output1 = new File("output1.txt");
//check whether the file's name already exists in the current directory
if(output1.exists())
{
System.out.println("File already exists");
System.exit(0);
}
PrintWriter pw = new PrintWriter(output1);
pw.println("The sum is " + sum);
pw.close();
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}
}//end main method
}//end ReadWriteTextFileExample

最佳答案

file 变量在 try block 中声明。它超出了 catch block 的范围。 (虽然在这种情况下不会发生,但想象一下如果在执行甚至到达变量声明之前抛出异常。基本上,您不能访问在中声明的 catch block 中的变量相应的 try block 。)

您应该在 try block 之前声明它:

File file = new File("input1.txt");
try
{
...
}
catch(FileNotFoundException exception)
{
System.out.println("The file " + file.getPath() + " was not found.");
}
catch(IOException exception)
{
System.out.println(exception);
}

关于java - 在 Java 中读取文件时 FileNotFoundException 捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com