5

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

}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Hilbis White
  • 179
  • 2
  • 2
  • 7
  • http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html. The 10 first results returned by Google when searching for "how to read lines from a file in Java" answer your question. – JB Nizet Nov 25 '14 at 15:06
  • Google can be very useful, from time to time ;) – Maksym Nov 25 '14 at 15:06

7 Answers7

6

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.

brso05
  • 13,142
  • 2
  • 21
  • 40
2
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
    System.err.println(ex.toString());
    //here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
    //read line by line with the readLine() method
    while ((line = reader.readLine()) != null && counter < N) { 
    //check also the counter if it is smaller then desired amount of lines to read
        array.add(line); //add the line to the ArrayList of strings
        counter++; //update the counter of the read lines (increment by one)
    }
    //the while loop will exit if:
    // there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
    // OR the desired amount of line was correctly read
    reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
    System.err.println(ex.toString());
}
WoDoSc
  • 2,598
  • 1
  • 13
  • 26
  • Why to use `ArrayList`? – Luiggi Mendoza Nov 25 '14 at 15:12
  • @LuiggiMendoza Because his problem is to read N lines of a text file, independently by the content of the file itself. I think that the fact that he illustrated numbers is just for give us an example – WoDoSc Nov 25 '14 at 15:15
  • I don't think so. OP's intention is very explicit. The only part OP cannot realize how to do is read the content of the file. The rest of the code is just waiting for that missing piece to solve the puzzle. – Luiggi Mendoza Nov 25 '14 at 15:17
2

See this How to read a large text file line by line using Java?

I think this will work:

BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    int i = 0;
    while ((line = br.readLine()) != null)
    {
        if (i < 5)
        {
            // process the line.
            i++;
        }
    }
    br.close();
Community
  • 1
  • 1
Romy
  • 272
  • 2
  • 11
2

You can do this with:

try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
    List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
    // do something with the list here
}

As complete example as JUnit test:

public class ReadFirstLinesOfFileTest {

    @Test
    public void shouldReadFirstTenNumbers() throws Exception {
        Path p = Paths.get("numbers.txt");
        Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());

        try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
            List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
            List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
            Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
        }
    }
}
baumato
  • 358
  • 3
  • 13
1
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
        new InputStreamReader(new FileInputStream("numbers.txt")))) {
    for (int i = 0; i < 5; ++i) { // Loops 5 times
        String line = in.readLine();
        if (line == null) [ // End of file?
            break;
        }
        // line does not contain line-ending.
        int num = Integer.parseInt(line);
        array.add(i);
    }
} // Closes in.
System.out.println(array);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
    myList.add(fileScanner.nextDouble());
}

Make sure you have "numberOfLinesToRead" lines in your file.

newbieee
  • 440
  • 1
  • 5
  • 17
0
  BufferedReader br = new BufferedReader(new FileReader(file));
  List<String> nlines = IntStream.range(0, hlines)
    .mapToObj(i -> readLine(br)).collect(Collectors.toList());

  String readLine(BufferedReader reader) { 
    try { 
      return reader.readLine();
    } catch (IOException e) { 
      throw new UncheckedIOException(e);
    }
  } 
Chandra
  • 21
  • 2