将文件拆分为n行,并将它们添加到字符串的ArrayList中

时间:2018-05-17 16:53:17

标签: java string file arraylist

我想以8行分割文件并将它们放入字符串的ArrayList中。

例如,这个文件:

public class Example {
    private int result = 2 + 1;
    private int result2 = 3 * 2;
    private int result3 = 3 + 3;

    private int result4 = 5 + 1 * 74;
    private String a = "This is a string";
    System.out.println("Just a print");
    int b = 12;

    System.out.println("Another print");
}

将导致以下两个条目ArrayList:

ArrayList<String> fileSplitted = { "public class Example {\nprivate int result = 2 + 1;\nprivate int result2 = 3 * 2;\nprivate int result3 = 3 + 3;\n\nprivate int result4 = 5 + 1 * 74;\nprivate String a = "This is a string";\nSystem.out.println("Just a print");" ; "int b = 12;\n\nSystem.out.println("Another print");\n}" }

所以我写了这个函数:

public static ArrayList<String> splitFile(File file) throws FileNotFoundException {
        ArrayList<String> fileSplitted = new ArrayList<String>();
        ArrayList<String> fileSplittedReturn = new ArrayList<String>();
        Scanner input = new Scanner(file);
        StringBuilder tmp = new StringBuilder();
        int count = 0;
        int countTotal = 0;

        while (input.hasNextLine()) {
            fileSplitted.add(input.nextLine());
        }

        for (String s : fileSplitted) {
            if (count < 8 && countTotal != fileSplitted.size() - 1) {
                tmp.append(s);
                count++;
            } else if (count == 8 && countTotal != fileSplitted.size() - 1) {
                fileSplittedReturn.add(tmp.toString());
                tmp.setLength(0);
                tmp.append(s);
                count = 1;
            } else if (countTotal == fileSplitted.size() - 1) {
                fileSplittedReturn.add(tmp.toString());
            }
            countTotal++;
        }

        return fileSplittedReturn;
    }

即使它有效(我还没有发现任何错误,但我无法确定),我认为它有点沉重,而且不易读取。

有没有办法让我修饰这个功能,让它更轻巧一点?

1 个答案:

答案 0 :(得分:0)

从文件中读取所有行后(如果我们已经知道文件不会太大,这是一种可接受的方法)

我会使用

之类的东西对行进行分组
public static List<String> groupLines(List<String> lines, int groupSize){
    int remaining = lines.size() % groupSize;
    int nbSplit = lines.size() / groupSize;

    List<String> target = new ArrayList<>();

    for(int i = 0; i < nbSplit; i++){
        target.add(getLines(lines,i * groupSize, groupSize));
    }

    if(remaining > 0){
        target.add(getLines(lines, nbSplit * groupSize, remaining));
    }

    return target;
}

private static String getLines(List<String> lines, int from, int size){
    return lines.stream()
            .skip(from)
            .limit(size)
            .collect(Collectors.joining("\n"));
}