以下是输入文本文件示例:
some text
one more line of text
another line
and one more
1 23 3
2 34 4
5 12 4
3 23 8
我需要提取每列数值并对其执行一些数学运算。
这是我迄今为止所尝试过的:
Path inputFile = Paths.get(args[0]);
try{
ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
ArrayList<String []> columns = new ArrayList<>();
for(String line : lines){
columns.add(line.split("\\s"));
}
// Now for each line you have columns.
for(String [] s : columns){
System.out.println(Arrays.toString(s));
}
但它不对,我无法摆脱这种僵局。任何帮助将不胜感激..
答案 0 :(得分:1)
我会说...
for(String line : lines){
// Just add this condition
if(line.matches("^[0-9]"){
// then process the way you want to...
}
}
希望这会有所帮助......
编辑:
Path inputFile = Paths.get(args[0]);
try{
ArrayList<String> lines = (ArrayList<String>) Files.readAllLines(inputFile, Charset.defaultCharset());
ArrayList<String []> columns = new ArrayList<>();
for(String line : lines){
if(line.matches("^[0-9]")){
System.out.println("Line:"+line);
String[] colms = line.split("\\s+");
columns.add(colms);
for (int i = 0; i < colms.length; i++) {
String temp = colms[i];
System.out.println("Colmns:"+i+":"+temp);
// process temp one by one
}
}
}
}catch(Exception ex){
ex.printStackTrace();
System.out.println("Exception...");
}