2012-02-11 5 views
0

저는 파일을 읽는 데 도움이되는 자바 초보자입니다. 여기에 제가 사용하고있는 코드가 있습니다.Java에서 .txt 파일 읽기 관련 문제

소스 :

public void Escanear() 
{ 

    Scanner sc=new Scanner(new File("inicio.txt")); 
    while(sc.hasNext()) 
    { 
     String token = sc.next(); 

     if (token.equals("Pared")) 
     { 
      int i=sc.nextInt(); 
      int j=sc.nextInt(); 

      _mat=new Pared[i][j]; 
     } 

     else if(token.equals("Fantasma")) 
     { 
      int i=sc.nextInt(); 
      int j=sc.nextInt(); 

      _mat=new Fantasma[i][j]; 
     } 
    } 
} 

오류 :

C:\Users\User\Documents\Jorge\Clases UNIMET\Trimestre 5\Estructuras de Datos\Proyecto Pacman\JuegoPacman.java:28: error: unreported exception FileNotFoundException; must be caught or declared to be thrown 
     Scanner sc=new Scanner(new File("inicio.txt")); 

내가 java.io.FileNotFoundException을 가져온, 나는 이미 같은 폴더에있는 .txt 파일을 열었습니다 내가 편집하고있는 수업처럼 ... 어떻게 고칠 수 있을까? 감사.

+1

올바른 경로를 지정하십시오. 'D :/jmd/sample.log'와 같습니다. – Arung

+0

여기에 파일의 전체 경로를 게시하십시오. 국가 기호가 포함되어 있습니까? –

답변

1

error: unreported exception FileNotFoundException; must be caught or declared to be thrown입니다. 컴파일 오류입니다. 즉, 코드에서 메서드 호출 중 하나가 FileNotFoundException을 throw하도록 선언되었음을 의미합니다.

프로그램이 실행되지 않아 파일 위치와 관련이 없습니다.

Scanner constructor 28 번째 줄에서 호출하면 잠재적으로 FileNotFoundException이 throw됩니다.

즉,이 잠재적으로 발생하는 예외를 처리해야합니다. escanear 메서드 정의 (대문자 btw로 시작하지 않아야 함)에 throws FileNotFoundException을 추가하거나이 메서드 호출로 줄을 try-catch으로 묶습니다.

+0

문제가 해결되었습니다. 감사합니다. – Jmdjorgeek

0

컴파일하려면 FileNotFoundException을 catch하거나 throw해야합니다.

예 :

"foo\dir\myfile.txt" 

당신은 탈출해야합니다 때문에 같은 소스 코드의 경로에

The thing is that when I give it the full path name, it shows 9 illegal escape character errors

이것은 아마도 : 당신은 코멘트에 말을

Scanner sc; 
try { 
    sc = new Scanner(new File("inicio.txt")); 
} catch (FileNotFoundException e) { 
    System.exit(1); 
} 
+0

"throws"로 해결, – Jmdjorgeek

0

이 법적인 자바를 만들기위한 백 슬래시 :

(210)
"foo\\dir\\myfile.txt" 

(또는 슬래시 사용 -이 심지어 윈도우에서 잘 작동 생각)

자바 특수 문자 이스케이프 시퀀스로 인코딩으로 \d\m이 의도 생각한다.

줄 바꿈을 위해 \n과 같은 유효한 이스케이프 시퀀스 목록을 보려면 http://docs.oracle.com/javase/tutorial/java/data/characters.html을 참조하십시오.

+0

님이 이미 FileNotFoundException을 던지면서 해결해 주셔서 감사합니다. 어쨌든 고맙습니다. – Jmdjorgeek