텍스트 파일에서 정수를 읽은 다음 출력 파일에 합계를 출력하는 간단한 프로그램을 작성하려고합니다. 내가 얻는 유일한 오류는 내 catch 블록 38 줄에 있습니다. "컴파일되지 않은 문제 : 파일을 확인할 수 없습니다." "file"은 입력 파일 객체의 이름입니다. 이 예외 블록을 주석 처리하면 프로그램이 제대로 실행됩니다. 모든 조언을 부탁드립니다!FileNotFoundException Java에서 파일을 읽을 때 catch 오류가 발생했습니다.
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
좋아, 그 의미가 있습니다. 이 첫 번째 부분은 실제로 교수가 제공 했으므로 try 블록 위로 선을 이동시키는 화살표를 그릴 것이라고 생각합니다. 나는 이것이 실수인지, 아니면 우리가 그것을 잡기로되어 있는지 확실하지 않습니다. 감사! – Johnny