简体   繁体   English

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

[英]Java read specific file store in arraylist

Suppose I would like to read input text file into lists. 假设我想将输入文本文件读入列表。

File contents: 文件内容:

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

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

How do I avoid reading the comments and store each line in a proper order? 如何避免阅读注释并以正确的顺序存储每一行​​?

Ex: 例如:

task = {A,B,C,D}

duration = {1,2,3,4}

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

How do I avoid reading the comments and store each line in a proper order? 如何避免阅读注释并以正确的顺序存储每一行​​?

The simplest way to avoid comments is to use a simple method for denoting a comment. 避免评论的最简单方法是使用一种简单的方法来表示评论。 Eg starting a line with # is often used to denote comments in simple scripting languages. 例如,以#开头的行通常用于表示简单脚本语言的注释。 Thus there is no need to parse for open/close comment contexts as inputs can be treated as whole lines. 因此,无需分析打开/关闭注释上下文,因为可以将输入视为整行。

Pick that specific file from the list. 从列表中选择该特定文件。 Read it line by line. 逐行阅读。 Check each line if it is a comment. 检查每一行是否为注释。 If Yes, Skip the line and continue. 如果是,请跳过该行并继续。 else split the line into words and store those words into an array of String. 否则将行拆分为单词,然后将这些单词存储到String数组中。 Put each element to its corresponding list. 将每个元素放入其对应的列表。 Note: The conditon if (raw.length < 3) is just used to handle the enter character as you have one at the end of line 4. 注意:条件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