解析文本文件java中的每一行

我有一个文本文件,其中包含以下行:

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 

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

 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 lines = Files.readAllLines(file, Charset.defaultCharset()); ArrayList 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))); } 

这是因为String.split使用正则表达式 。

在正则表达式中, | character是一个特殊字符,表示字符either the pattern on the left OR on the right 。 必须使用反斜杠( \\ )进行转义

正确的语法是:

 String[] fields = line.split("\\|"); 

另外,拿nto我没有看到for循环的问题,但是这也需要修复,这就是为什么ArrayOutOfBoundsException弹出它丑陋的脑袋……

 for(int i=0;i<=fields.length;i++) 

需要是

 for(int i=0;i 

('<='必须是'<')

你的正则表达式的问题也在其他答案中指出。

| 是regex中的一个特殊字符,它作为OR运算符,你需要使用以下命令来转义表达式:

 String[] fields = line.split("\\|"); 

而不是for(int i=0;i<=fields.length;i++){ use for(int i=0;i so在条件中使用<而不是<=。

您似乎在以下行中存在边界问题:

 for(int i=0;i<=fields.length;i++){ System.out.println(fields[i]); } 

应该

 for(int i=0;i 

应小于: for(int i=0;i