我正在尝试从java中的文件中练习阅读文本。我很困扰我如何读取N行数量,比如文件中的前10行,然后在ArrayList
中添加行数。如何从文件中读取N行数量?
说例如,该文件包含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
}
http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html。 Google在搜索“如何从Java文件读取文件”时返回的10个第一个结果回答了您的问题。 – 2014-11-25 15:06:06
谷歌可能会非常有用,不时;) – Maksym 2014-11-25 15:06:13