2011-12-26 5 views
1

다음 코드를 실행하여 텍스트 파일을 읽는 중입니다. 나는 자바에 상당히 익숙하며 스스로 프로젝트를 만들려고 연습하고있다. 다음 코드는 원래 텍스트 파일을 읽으려는 시도에서 발견 된 것으로부터 약간 수정되었지만 때로는 예외를 잡을 때도 있습니다. 읽으려고하는 텍스트 파일은 "hello world"라고만 표시됩니다. 텍스트 파일을 찾지 않아야한다고 가정합니다. 소스 코드와 동일한 폴더에 넣었고 소스 패키지에 나타납니다 (netbeans btw 사용). 다르게 가져올 필요가 있지만 더 자세한 정보를 찾을 수 없습니다. 내 코드가 여기에 관련된 경우에 그것은 아래에 있습니다.예외가 발생하는 이유

package stats.practice; 

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

public final class TextCompare { 

    String NewString; 

    public static void main() { 
     try { 
      BufferedReader in = new BufferedReader(new FileReader("hello.txt")); 
      String str; 
      while ((str = in.readLine()) != null) { 
       System.out.println(str); 
      } 
      in.close(); 
     } catch (IOException e) { 
     } 
     System.out.println("Error"); 
    } 
} 

답변

2

첫 단계 교체 또한

catch (IOException e) { e.printStackTrace(); } 

과 함께 코드

catch (IOException e){} 

아래 대체

main() 

main(String[] args) 

정확한 이유를 알려줍니다. 그런 다음 실제 이유를 풀어야합니다.

이제 Netbeans의 경우 파일 hello.txt이 Netbeans 프로젝트에 있어야합니다. like

<project_dir> 
    | 
    -->hello.txt 
    -->build 
    -->src 
+0

고맙습니다. 텍스트 파일의 위치를 ​​교체하는 것이 전부였습니다. – Zombian

3

매번 예외를 반드시 잡을 필요는 없습니다. System.out.println("Error"); 문이 catch 블록 외부에 있습니다. 따라서 프로그램이 실행될 때마다 실행됩니다.

이 해결 중괄호 ( catch (IOException e) {System.out.println("Error");})

7

catch 블록 닫는 괄호가 잘못 인 내를 이동한다. 그것을 System.out.println("Error"); 아래로 이동하십시오. 방어 프로그램의 문제로

public static void main(String[] args) { 
    try { 
     BufferedReader in = new BufferedReader(new FileReader("hello.txt")); 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { // <-- from here 
     System.out.println("Error"); 
     // or even better 
     e.printStackTrace(); 
    } // <-- to here 
} 

(전 자바 7 이상)을해야 finally 블록에서 항상 가까운 자원 : 당신이 자바 7을 사용하는 경우

public static void main(String[] args) { 
    BufferedReader in = null; 
    try { 
     in = new BufferedReader(new FileReader("hello.txt")); 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (in != null) { 
      try { 
       in.close(); 
      } catch (Exception e) {} 
     } 

     // or if you're using Google Guava, it's much cleaner: 
     Closeables.closeQuietly(in); 
    } 
} 

것은, 당신이 활용할 수 있습니다 try-with-resources를 통해 자동 자원 관리 :

public static void main(String[] args) { 
    try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) { 
     String str; 
     while ((str = in.readLine()) != null) { 
      System.out.println(str); 
     } 
     in.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

예,하지만 문제가 무엇인지 알 수 있도록 오류보다 나은 것을 인쇄해야합니다. –

+0

예, 편집 ... –

+0

+1, 당신은 빠르다! –

1

당신은 거의 항상 나쁜 생각 빈 catch 블록을 가지고있다. 여기에 넣으십시오.

... catch (IOException ex) { 
    ex.printStackTrace(); 
} 

그리고 빠르게 진행되고 있습니다.

관련 문제