java想读取一个txt文件,按行读取,然后把每一行按中间第一个空格分成2个字符串,分别用数组保存起来。

请问应该怎么写
2024-12-19 05:43:31
推荐回答(1个)
回答1:

试试
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class $ {
public static void main(String[] args) throws FileNotFoundException {
String path = "D:/a.txt";
Scanner in = new Scanner(new File(path));
List data = new ArrayList();
while (in.hasNextLine()) {
// 取第一行
String s = in.nextLine();
int idx = s.indexOf(" ");
String s0 = s.substring(0, idx);
String s1 = s.substring(idx + 1, s.length() - 1);
String[] arrs = { s0, s1 };
data.add(arrs);
}
for (int i = 0; i < data.size(); i++) {
String[] arr = (String[]) data.get(i);
System.out.println("第" + (i + 1) + "行是:" + arr[0] + "\t" + arr[1]);
}
}
}