我不太确定如何解释我的问题,但我会尽力而为。例如,我有一个包含 100 个数字的文件,是否可以从这个 100 个数字的文件中读取第 25-50 行。
要从头开始读取 N 个数量,我会做这样的事情;
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++;
}
但我不太确定如何从给定的行开始阅读,例如第 25-50 行或第 25-75 行或第 75-100 行等
非常感谢任何帮助,如果我的问题不清楚,请告诉我。
编辑:
文件中的一些数据:
- 1.45347,1.1545,1.2405
- 1.467,1.4554,1.2233
- 1.4728,1.3299,1.1532
- 1.131,1.5139,1.0044
- 1.4614,1.7373,1.6235
- 1.654,1.5544,1.61147
最佳答案
byte[] inputBytes = "line 1\nline 2\nline 3\ntok 1 tok 2".getBytes();
Reader r = new InputStreamReader(new ByteArrayInputStream(inputBytes));
BufferedReader br = new BufferedReader(r);
Scanner s = new Scanner(br);
System.out.println("First line: " + br.readLine());
System.out.println("Second line: " + br.readLine());
System.out.println("Third line: " + br.readLine());
System.out.println("Remaining tokens:");
while (s.hasNext())
System.out.println(s.next());
并像 Astra 建议的那样添加一个 while 循环
关于java - 从 java 文件中读取 N 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28656611/