【发布时间】:2014-11-25 15:01:05
【问题描述】:
我正在尝试练习从 java 文件中读取文本。我不知道如何读取 N 行,比如文件中的前 10 行,然后将这些行添加到 ArrayList 中。
比如说文件包含1-100个数字,像这样;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
我想读取前 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
}
【问题讨论】:
-
docs.oracle.com/javase/tutorial/essential/io/charstreams.html。 Google 在搜索“如何从 Java 中读取文件中的行”时返回的前 10 个结果回答了您的问题。
-
Google 有时会非常有用;)
标签: java for-loop arraylist bufferedreader fileinputstream