2013-03-02 1 views
0

텍스트 파일에서 정수를 읽은 다음 출력 파일에 합계를 출력하는 간단한 프로그램을 작성하려고합니다. 내가 얻는 유일한 오류는 내 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 

답변

2

범위는 블록을 기반으로합니다. 블록 안에 선언 한 변수는 동일한 블록의 끝까지 범위 내에 있습니다. 당신이 당신의 try 블록 전에 file을 선언하는 경우

try 
{ // start try block 
    File file = ...; 

} // end try block 
catch (...) 
{ // start catch block 

    // file is out of scope! 

} // end catch block 

그러나,이 범위에 남아 :

File file = ...; 

try 
{ // start try block 


} // end try block 
catch (...) 
{ // start catch block 

    // file is in scope! 

} // end catch block 
+0

좋아, 그 의미가 있습니다. 이 첫 번째 부분은 실제로 교수가 제공 했으므로 try 블록 위로 선을 이동시키는 화살표를 그릴 것이라고 생각합니다. 나는 이것이 실수인지, 아니면 우리가 그것을 잡기로되어 있는지 확실하지 않습니다. 감사! – Johnny

3

file 변수 try 블록 내에서 선언된다. catch 블록의 범위를 벗어났습니다. (이 경우에는 발생할 수 없지만, 실행이 변수 선언에 도달하기 전에 예외가 발생했는지 상상해보십시오. 기본적으로 블록에 선언 된 catch 블록의 변수에 액세스 할 수 없습니다.

대신 전에 그것을 try 블록을 을 선언해야합니다 : 자바에서

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); 
} 
관련 문제