解析文本文件java中的每一行 [英] parsing each line in text file java

查看:69
本文介绍了解析文本文件java中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下几行的文本文件:

I have a text file that has the following lines:

150004|2012|12|15|0|0|3|0|0|-3.2411|83.9962|156.3321|1.1785|205.3125|2.0599
150004|2012|12|15|0|10|3|0|0|-3.4206|85.9575|150.4877|1.4142|226.7578|2.4276
150004|2012|12|15|0|20|3|0|0|-2.2696|86.2675|149.3848|2.1553|225.7031|3.4387

每个"|"符号表示它有一列.我必须从"|"内部的每一行中提取信息迹象.当我尝试以下代码时:

every '|' sign indicates it has a column. I have to extract the info from each line that is inside of '|' signs. When I try the following code:

File filer = new File("C:\\Users\\Ali Y. Akgul\\Desktop\\150004_15122012_G.txt");
        try (BufferedReader reader = new BufferedReader(new FileReader(filer))) {
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                String[] fields = line.split("|");
                // process fields here
                for(int i=0;i<=fields.length;i++){
                    System.out.println(fields[i]);
                }
            }
        }
}

它给了我

1
5
0
0
0
4
|
2
0
1
2
|
1
2
|
1
5
|
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 76
0
|
0
|
3
|
0
|
0
|
-
3
.
2
4
    at testenv.TestEnv.main(TestEnv.java:31)
1
1
|
8
3
.
9
9
6
2
|
1
5
6
.
3
3
2
1
|
1
.
1
7
8
5
|
2
0
5
.
3
1
2
5
|
2
.
0
5
9
9
Java Result: 1

如何正确解析?

推荐答案

尝试一下:

Path file = Paths.get("C:\\Users\\Ali Y. Akgul\\Desktop\\150004_15122012_G.txt");

ArrayList<String> lines = Files.readAllLines(file, Charset.defaultCharset());
ArrayList<String []> columns = new ArrayList<>();
for(String line : lines){
    columns.add(line.split('\|'));
}

// Now for each line you have columns.
for(String [] s : columns){ 
    System.out.println(Arrays.toString(s));
}

// To get only the values for column 8 onwards (in response to your comment)
for(String [] s : columns){ 
    String [] sublist = Arrays.copyOfRange(s, 8, s.length);
    System.out.println(Arrays.toString(sublist));
}

// To get only the columns from line 8 onwards
for(int i = 0; i < columns.size(); i++){
    System.out.println(Arrays.toString(columns.get(i)));
}        

这篇关于解析文本文件java中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆