Search code examples
javaarraysfilejava.util.scannerbufferedreader

Reading N lines from a file in java?


I am not quite sure how to explain my question but I will try my best. Say for example, I have a file containing 100 numbers, is it possible to read lines 25-50 from this 100 numbers file.

To read N amount from begining, I would do something like this;

ArrayList<Double> array = new ArrayList<Double>();
 Scanner input = new Scanner(new File("numbers.txt"));
 int counter = 0;
 while(input.hasNextLine() && counter < 10)
 {
     array.add(Double.parseDouble(input.nextLine()));
     counter++;
 }

But I am not quite sure how I can go about start reading from a given line e.g. lines 25-50 or 25-75 or 75-100 etc.

Any help is much appreciated and please let me know if my question is not clear.

edit:

Some data in the file:

  • 1.45347,1.1545,1.2405
  • 1.467,1.4554,1.2233
  • 1.4728,1.3299,1.1532
  • 1.131,1.5139,1.0044
  • 1.4614,1.7373,1.6235
  • 1.654,1.5544,1.61147

Solution

  • byte[] inputBytes = "line 1\nline 2\nline 3\ntok 1 tok 2".getBytes();
    Reader r = new InputStreamReader(new ByteArrayInputStream(inputBytes));
    
    BufferedReader br = new BufferedReader(r);
    Scanner s = new Scanner(br);
    
    System.out.println("First line:  " + br.readLine());
    System.out.println("Second line: " + br.readLine());
    System.out.println("Third line:  " + br.readLine());
    
    System.out.println("Remaining tokens:");
    while (s.hasNext())
        System.out.println(s.next());
    

    and add a while loop like Astra suggested