我在一个文件中有这些行:
101 xxx 3 yyy
102 aaa 2 bbb
103 ppp 3 qqq
104 iii 5 jjj
我想将每一行的每个元素放在一个数组中,例如
int[] par1 = {101,102,103,104}
String[] par2 = {"xxx", "aaa", "ppp", "iii"}
int[] par3 = {3,2,3,5}
String[] par4 = {"yyy", "bbb", "qqq", "jjj"}
使用 Guava / Apache Commons 等阅读行:
结果是:
List<String> lines;
接下来(使用lines
):
List<Integer> par1 = new ArrayList();
List<String> par2 = new ArrayList();
List<Integer> par3 = new ArrayList();
List<String> par4 = new ArrayList();
try {
for(String line : lines) {
String[] elements = line.split(" ");
if(elements.length == 4) {
par1.add(Integer.valueOf(element[0]));
par2.add(element[1]));
par3.add(Integer.valueOf(element[2]));
par4.add(element[3]));
}
else {
throw new Exception("Conversion failed");
}
}
}
catch(NumberFormatException ex) {
throw new Exception("Conversion failed");
}
// Convert ArrayList to Array if you need to.
像这样的东西应该可以工作(没有测试)
List<String> lines = Files.readAllLines(Paths.get("1.txt"), StandardCharsets.UTF_8);
int[] par1 = new int[lines.size()];
String[] par2 = new String[lines.size()];
int[] par3 = new int[lines.size()];
String[] par4 = new String[lines.size()];
for(int i = 0; i < lines.size(); i++) {
String[] a = lines.get(i).split(" +");
par1[i] = Integer.parseInt(a[0]);
par2[i] = a[1];
par3[i] = Integer.parseInt(a[2]);
par4[i] = a[4];
}