繁体   English   中英

Java读取arraylist中的特定文件存储

[英]Java read specific file store in arraylist

假设我想将输入文本文件读入列表。

文件内容:

/* ignore comments */
/*TaskID <space> Duration <space> Dependency <comma> <Dependency>...*/

A 1 
B 2 A(-1)
C 3 B,A
D 4 D

如何避免阅读注释并以正确的顺序存储每一行​​?

例如:

task = {A,B,C,D}

duration = {1,2,3,4}

dependency = {, A(-1), BA, D}

如何避免阅读注释并以正确的顺序存储每一行​​?

避免评论的最简单方法是使用一种简单的方法来表示评论。 例如,以#开头的行通常用于表示简单脚本语言的注释。 因此,无需分析打开/关闭注释上下文,因为可以将输入视为整行。

从列表中选择该特定文件。 逐行阅读。 检查每一行是否为注释。 如果是,请跳过该行并继续。 否则将行拆分为单词,然后将这些单词存储到String数组中。 将每个元素放入其对应的列表。 注意:条件if (raw.length < 3)仅用于处理enter字符,因为在第4行的末尾有一个。

public class ReadContents {

    public static void main(String[] args) {
        ArrayList<File> files = new ArrayList();

        ArrayList<String> tasks = new ArrayList();
        ArrayList<String> hrs = new ArrayList();
        ArrayList<String> others = new ArrayList();
        String[] raw;
        files.add(new File("File path"));
        try (BufferedReader br = new BufferedReader(new FileReader(files.get(0)))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("/*") | line.equals("")) {
                    continue;
                } else {
                    raw = line.split("\\s+");
                    if (raw.length < 3) {
                        tasks.add(raw[0]);
                        hrs.add(raw[1]);
                        others.add("");
                    }else{
                        tasks.add(raw[0]);
                        hrs.add(raw[1]);
                        others.add(raw[2]);
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM