Java:将文本文件拆分为多个List

时间:2015-07-04 20:48:30

标签: java

我正在寻找一种将文本文件拆分成一组ArrayList的有效方法。文本文件是一个线程转储,我想为每个线程创建一个List。每个线程都用空行分隔。 例如,采用以下文件:

"management-handler-thread - 66" prio=10 tid=0x00007fe960111000 nid=0x4cea waiting on condition [0x00007fe96c25c000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000006019cbbd0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:226)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2082)
        at java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:467)

"management-handler-thread - 65" prio=10 tid=0x00007fe968185800 nid=0x4ce9 waiting on condition [0x00007fe96c35d000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000006019cbbd0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:226)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2082)
        at java.util.concurrent.LinkedBlockingQueue.poll(LinkedBlockingQueue.java:467)

第一个列表应包含:

"management-handler-thread - 66" prio=10 tid=0x00007fe960111000 nid=0x4cea waiting on condition [0x00007fe96c25c000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
. . .

第二个List应该包含:

"management-handler-thread - 65" prio=10 tid=0x00007fe968185800 nid=0x4ce9 waiting on condition [0x00007fe96c35d000]
   java.lang.Thread.State: TIMED_WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
. . . .

你会建议做什么? (迭代,正则表达式..) 感谢

1 个答案:

答案 0 :(得分:3)

不需要正则表达式,只需逐行读取文件......

List<List<String>> dumpedThreads = new ArrayList<>();
try (FileReader fr = new FileReader("path/to/thread-dump.txt")) {
    try (BufferedReader br = new BufferedReader(fr)) {
        List<String> thisThread = null;
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            if (line.trim().length() == 0) {
                thisThread = null;
            } else {
                if (thisThread == null) {
                    thisThread = new ArrayList<>();
                    dumpedThreads.add(thisThread);
                }
                thisThread.add(line);
            }
        }
    }
}