2014-07-17 5 views
0

자바 클래스의 탭 구분 파일에서 입력을 읽는 중입니다. 파일이 제대로 열리 며 파일의 정보가 올바로 읽혀지는 것 같습니다. 파일의 모든 줄이 예상대로 화면에 출력되지만 다음 파일 끝에 한 줄 더 인쇄하려고하면 ArrayIndexOutOfBoundsException이 나타납니다. 1.Java의 파일 IO 예외

주석을 제거하면 유의할 가치가 있습니다 내가 sCurrentline의 값을 출력하고 split 배열의 출력을 주석 처리하는 줄에서 오류가 발생하지 않습니다.

코드 :

BufferedReader br = null; 

try { 
     String sCurrentLine; 

     br = new BufferedReader(new FileReader(fname)); 

     while ((sCurrentLine = br.readLine()) != null){ 

      String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields 

      System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: " 
      + values[2] + " Col4: " + values[3] + " Col5: " + values[4]); 

      //System.out.println(sCurrentLine); 

     } 
} catch (IOException e) { 
    System.out.println("IOException"); 
    e.printStackTrace(); 
} finally { 
    try { 
     if(br != null){ 
      br.close(); 
     } 
    } catch (IOException ex) { 
     System.out.println("ErrorClosingFile"); 
     ex.printStackTrace(); 
    } 
} 
+1

당신은 아마 파일의 끝에 여분의 빈 줄이 존재하지 않는 배열 위치를 읽는 것은 분명하다보십시오. 계속하기 전에'values'의 길이를 검사해야합니다. – Thilo

답변

1

코드가 좋아 보인다 ... 당신이 마지막에 빈 줄 바꿈을해야합니까?

while ((sCurrentLine = br.readLine()) != null){ 
    if (sCurrentLine.isEmpty() || sCurrentLine.startsWith(";")) // skip empty and comment lines 
     continue; 

    String[] values = sCurrentLine.split("\\t"); // are you sure the -1 is required? 
... 
} 
+0

놓친 ... 좋은 전화 – Deslyxia

2

마지막 줄의 요소 수가 다른 줄과 다릅니다. 마지막 행을 분할 한 후 존재하지 않는 배열의 필드에 액세스하려고 시도합니다. 이는 http://docs.oracle.com/javase/7/docs/api/java/lang/ArrayIndexOutOfBoundsException.html 예외로 표시됩니다. 배열의 필드에 액세스하기 전에 예상되는 항목의 수가 있는지 확인해야합니다. 이처럼 :

BufferedReader br = null; 

try { 
    String sCurrentLine; 
    br = new BufferedReader(new FileReader(fname)); 

    while ((sCurrentLine = br.readLine()) != null){ 
     String[] values = sCurrentLine.split("\\t", -1); // don't truncate empty fields 

     if (5 == values.length) { 
      System.out.println("Col1: " + values[0] + " Col2: " + values[1] + " Col3: " 
      + values[2] + " Col4: " + values[3] + " Col5: " + values[4]); 
     } 

     // System.out.println(sCurrentLine); 
    } 
} catch (IOException e) { 
    System.out.println("IOException"); 
    e.printStackTrace(); 
} finally { 
    try { 
     if(br != null){ 
      br.close(); 
     } 
    } catch (IOException ex) { 
     System.out.println("ErrorClosingFile"); 
     ex.printStackTrace(); 
    } 
} 
0

String[] values = "".split("\\t", -1); // don't truncate empty fields 
    int index=1; 
    StringBuffer sb = new StringBuffer(); 
    for (String value : values) { 
     sb.append("Col"+index+":").append(value).append(" "); 
     index++; 
    } 
    System.out.println(sb.toString()); 

당신이