2014-12-13 1 views
1

프로젝트를 만들 때마다 파일 관리자를 다시 작성하기가 너무 어려워서 파일 IO 라이브러리를 만들고 있습니다. 내가 그것을 실행하면, 내가 얻을 :null을 출력하는 파일 판독기 라이브러리

null 
null 
null 

그것은 많은 행이 파일에 얼마나 찾았지만 널 (null)로 모두 넣습니다. 이 문제를 어떻게 해결할 수 있습니까?

파일 관리자 :

package textfiles; 
import java.io.IOException; 
import java.io.FileReader; 
import java.io.BufferedReader; 

public class KezelFile { 

    private String path; 
    BufferedReader buff; 

    public KezelFile(String filePath) throws IOException { 
     path = filePath; 
     openFile(); 
    } 

    public void openFile() throws IOException { 
     FileReader read = new FileReader(path); 
     buff = new BufferedReader(read); 
    } 

    public String[] toStringArray() throws IOException { 

     int numberOfLines = readLines(); 
     String[] textData = new String[numberOfLines]; 

     int i; 

     for (i=0; i < numberOfLines; i++) { 
     textData[i] = buff.readLine(); 

     } 
     return textData; 
    } 

    int readLines() throws IOException { 

     String lines; 
     int noLines = 0; 

     while ((lines = buff.readLine()) != null) { 
      noLines++; 
     } 

     return noLines; 
    } 

    public void closeFile() throws IOException { 
     buff.close(); 
    } 

} 

Main 클래스 :

package textfiles; 
import java.io.IOException; 

public class FileData { 

    public static void main(String[] args) throws IOException { 

     String filePath = "C:/test.txt"; 

     try { 
      KezelFile file = new KezelFile(filePath); 
      String[] aryLines = file.toStringArray(); 

      int i; 
      for (i=0; i < aryLines.length; i++) { 
      System.out.println(aryLines[i]); 
      } 
      file.closeFile(); 
     } 

     catch (IOException error){ 
      System.out.println(error.getMessage()); 
     } 

    } 

} 
+1

는 바퀴를 재발견하지 마십시오) - 아무도 사각형 바퀴를 필요로하지 않는다;

은 BTW 자바 (8) 당신은 아마이 Java8을 시도하는 시간이다

Files.lines(filename).forEach(System.out::println); 

를 작성할 수 있습니다. 특히 느린 펑크를 가진 사람은 아닙니다. ['Files'] (https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html) 유틸리티 클래스를 사용하십시오. –

답변

0

당신이 모든 라인을 읽은 후에는 파일을 다시 열 때까지, 다시 그 라인을 읽을 수 없습니다. readLine()이 다른 메소드에서 호출 되었기 때문에 판독기를 "재설정"하지 않습니다.

더 좋은 해결책은 파일을 한 번 읽는 것입니다. List<String>에있는 행을 읽거나 파일을 읽을 때 파일을 더 잘 처리하는 것이 좋으며 컬렉션도 필요하지 않습니다.

+0

더 나은 해결책은 기존 기능을 사용하는 것입니다 -'Files.readAllLines' 또는'Files.lines' ... –

+1

Java 7에서도'Files.readAllLines'를 사용할 수 있습니다 ... –

+0

@BoristheSpider Java 8, 예. Java 8이 없으면해야합니다.) –