How to read N amount of lines from a file?

Hilbis White picture Hilbis White · Nov 25, 2014 · Viewed 18k times · Source

I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.

Say for example, the file contains 1-100 numbers, like so;

- 1 
- 2 
- 3 
- 4 
- 5 
- 6 
- 7 
- 8 
- 9 
- 10 
- ....

I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.

ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));

for (double i = 0; i <= 5; ++i) {
    // I know I need to add something here so the for loop read through 
    // the file but I have no idea how I can do this
    array.add(i); // This is saying read 1 line and add it to arraylist,
    // then read read second and so on

}

Answer

brso05 picture brso05 · Nov 25, 2014

You could try using a Scanner and a counter:

     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++;
     }

This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.