如何从文件中读取N行?

Hil*_*ite 3 java for-loop arraylist fileinputstream bufferedreader

我正在尝试练习从 Java 文件中读取文本。我不太了解如何读取 N 行,比如文件中的前 10 行,然后将这些行添加到ArrayList.

例如,文件包含 1-100 个数字,如下所示;

- 1 
- 2 
- 3 
- 4 
- 5 
- 6 
- 7 
- 8 
- 9 
- 10 
- ....
Run Code Online (Sandbox Code Playgroud)

我想读取前 5 个数字,即 1,2,3,4,5 并将其添加到数组列表中。到目前为止,这是我设法做的,但我被卡住了,不知道现在该做什么。

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

}
Run Code Online (Sandbox Code Playgroud)

brs*_*o05 5

您可以尝试使用扫描仪和计数器:

     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++;
     }
Run Code Online (Sandbox Code Playgroud)

只要文件中有更多输入,这应该循环 10 行,将每行添加到数组列表中。