本文介绍了如何在java中的arraylist中的每个第3个元素之后添加换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序需要在arraylist中的每个第3个元素之后添加换行符。这是我的输入文件,其中包含以下数据:

My program need to add newline after every 3rd element in the arraylist. Here is my input file which contain the following data:

它会继续多行。

public class MyFile {

    private static final Pattern ISDN =Pattern.compile("\\s*ISDN=(.*)");

    public List<String> getISDNsFromFile(final String fileName) throws IOException {

        final Path path = Paths.get(fileName);
        final List<String> ret = new ArrayList<>();
        Matcher m;
        String line;
        int index = 0;
        try (
        final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);) {
            while ((line = reader.readLine()) != null) {
                m = ISDN.matcher(line);
                if (m.matches()) {
                    ret.add(m.group(1));
                    index++;
                    if(index%3==0){
                        if(ret.size() == index){
                            ret.add(m.group(1).concat("\n"));
                        }
                    }
                }
            }
            return ret;
        } 
    }
}


推荐答案

我使用新Java 7文件I / O将代码更改为读取,并更正了行分隔符的使用以及一些格式。在这里,我在完成后迭代列表。如果真的多,你可以在构建它时迭代它。

I changed your code to read using the "new" Java 7 files I/O and corrected the use of a line separator, along with some formatting. Here I iterate over the list after it was completed. If it is really long you can iterate over it while constructing it.

public class MyFile {

    private static final Pattern ISDN = Pattern.compile("\\s*ISDN=(.*)");
    private static final String LS = System.getProperty("line.separator");

    public List<String> getISDNsFromFile(final String fileName) throws IOException {

        List<String> ret = new ArrayList<>();
        Matcher m;

        List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        for (String line : lines) {
            m = ISDN.matcher(line);
            if (m.matches())
                ret.add(m.group(1));
        }
        for (int i = 3; i < ret.size(); i+=4)
            ret.add(i, LS);
        return ret;
    }
}

这篇关于如何在java中的arraylist中的每个第3个元素之后添加换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:06