Search code examples
javabufferedreaderreadlinefileinputstreaminputstreamreader

How do I read only one line of text file?


My program is reading all lines in the file but i just need the second one.

String line;
try (
    InputStream fis = new FileInputStream(source);
    InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
    BufferedReader br = new BufferedReader(isr)) {  
    while ((line = br.readLine()) != null) {
       System.out.println(line);
    }
}

Solution

  • If you only need the second line and you are sure the file always has at least two lines, you can just read twice and ignore the first time.

    br.readLine(); //read, but ignore
    System.out.println(br.readLine()); // read and output