2012-04-07 8 views
0

파일에 텍스트를 쓰는 응용 프로그램이 있습니다. 파일이 존재하지 않으면 생성됩니다.파일이 이미 존재할 때 프로그램을 시작하려고 할 때 예외가 발생합니다.

처음으로 응용 프로그램을 실행할 때 제대로 작동하고 파일이 만들어집니다. 그러나 후속 시간마다 응용 프로그램이 중단됩니다. 왜 그것이 두 번 이상 작동하지 않는지 설명해주십시오. 다음과 같이

내 코드

public class Apples { 

    Formatter x; 
    File file = new File("myfile.txt"); 

    public Apples() { 

     if (!file.exists()) { 
      try { 
       x = new Formatter("myfile.txt"); 
      } 
      catch (Exception e) { 
       System.out.println("There was an error creating the file"); 
      } 

      System.out.println("The file was created"); 
     } 
     else { 
      System.out.println("The file already exists"); 
      } 

     x.format("%s", "text"); 
     x.close(); 
    } 

    public static void main(String[] args) throws FileNotFoundException { 
     Apples a = new Apples(); 
    } 

} 
+0

어떤 오류가 발생합니까? –

+0

System.out.println ("error"); - System.out.println ("error :"+ e.getMessage());에서 전체 세부 정보를 인쇄하도록하십시오. –

답변

4

내가 파일이 이미 존재하는 경우 x에 값을 할당하지 않기 때문에 문제가 라인 x.format("%s", "text");NullPointerException 것으로 의심 ...입니다.

0

두 번째로 x은 초기화하지 않으므로 null입니다.

관련 문제