首页 > 解决方案 > 用换行符分割文本文件中的文本

问题描述

import java.io.*;
public class Wordcount {

    public static void main(String[] args) throws Exception {
        BufferedReader in = null;
        String[] splited = null;
        try {
            in = new BufferedReader(new FileReader("sample.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                splited = read.split("systemSerialNumber:");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {

            in.close();

        }

        System.out.println(splited[3]);
    }
}

“sample.txt”文件包含以下文本。

"2018-10-16 19:54:26.691 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1  - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.074 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1  - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.293 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1  - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2
"2018-10-16 19:54:27.296 [RawEventProcessor (2/2)] ERROR com.qolsys.iqcloud.processing.operators.RawEventProcessor1  - processRawPanelEvent():: SerialNumber systemSerialNumber: QV01D173700428AD is not mapped to any meid. {}",2

我收到数组索引超出范围异常的错误。以及为什么我得到这个异常,即使在拆分后我也不知道所有文本文件数据都存储在数组的一个索引中。剩下的都是空的。

堆栈跟踪 :

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at Task1.Wordcount.main(Wordcount.java:29)

标签: javafilebufferedreader

解决方案


检查结果的长度是否为 2。最后一行可能为空。

Path path = Paths.get("sample.txt");
Files.lines(path, Charset.defaultCharset())
    .forEach(line -> {
        String[] splitted = read.split("systemSerialNumber:");
        if (splitted.length == 2) {
            ...
        }
    });

作为无关信息:

        String[] splitted = read.split("systemSerialNumber:", 2);

将结果限制为最多 2 个元素,以防"systemSerialNumber:"出现不止一次。


推荐阅读