簡體   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