2017-11-19 2 views
-2

버퍼가있는 Reader 또는 Scanner를 사용하여 java의 텍스트 파일에서 처음 5 줄을 읽는 방법은 어떻게됩니까? 여기 그것은 텍스트 파일을 출력 내 코드텍스트 파일에서 5 줄을 읽는 방법

 final int assumedLineLength = 16; 


    File file = new File("src/hw7p1/Acronyms.txt"); 
    HashMap<String, String> hashMap = new HashMap<String, String>((int)(file.length()/assumedLineLength) * 2); 
    BufferedReader reader = null; 
    int linecount = 0 ; 
    String eachLine = null; 
    try { 
    reader = new BufferedReader(new FileReader(file)); 

    for (eachLine = reader.readLine(); 
      eachLine != null; 
      eachLine = reader.readLine()) { 
     hashMap.put(eachLine, " "); 
     linecount++; int i = 0; 

    } 


    TreeMap<String, String> sorted = new TreeMap<>(hashMap); 

    Set<Entry<String, String>> sortings = sorted.entrySet(); 

    for(Entry<String, String> sort : sortings){ 
     System.out.println(sort.getKey() + " " + sort.getValue()); 

    } 

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

} 이지만, 내가 뭘하려고하는 것은 처음 5 개 행을 인쇄 얻기 위해 단지이다. 어떤 도움을 주시면 감사하겠습니다.

+0

[mcve] – Oleg

+0

이 코드는 정확합니다. 독자 설정 방법에 오류가 있어야합니다. – Touniouk

+0

유효한 스트림을 텍스트 파일로여시겠습니까? –

답변

1

for 루프에서는 5 줄만 원한다면 eachLine을 사용하지 마십시오.

for(int i=0; i<5; i++) 
{ 
    //read the file 
} 
0
public String[] readLines(int noLines, String path) throws IOException { 

    FileReader fr = new FileReader(path); 
    BufferedReader br = new BufferedReader(fr); 
    String[] textData = new String[noLines]; 

    int i; 

    for (i=0; i < noLines; i++) { 

     textData[i] = br.readLine(); 

    } 

    br.close(); 

    return textData; 

} 
관련 문제