2017-11-19 21 views
-2

バッファ付きのリーダーまたはスキャナを使用して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; 

} 
関連する問題