用新行分割文本文件中的文本

时间:2018-10-29 09:01:20

标签: java file bufferedreader

fun mapmap f xss =
  let fun aux f [] _ = []
        | aux f ([]::xss) ys = rev ys :: aux f xss []
        | aux f ((x::xs)::xss) ys = aux f (xs::xss) (f x :: ys)
  in aux f xss [] end

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

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]);
    }
}

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

堆栈跟踪:

  

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

1 个答案:

答案 0 :(得分:0)

检查结果的长度为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);

"systemSerialNumber:"出现多次的情况下,结果最多只能包含2个元素。