如何在arrayList中存储文本文件内容..?

时间:2016-01-08 09:26:20

标签: java

我有如下文本文件我想将它存储在ArrayList中但问题是它没有相同的键值对,即最后2 [Param]有param4 = value4,param5 = value5。

如何在arrayList或map中存储它??

的test.txt

public class Task {

    static String Filepath = "C:\\Users\\Administrator\\Desktop\\TASK\\test.txt";
    static ArrayList<String> list1;
    static ArrayList<String> list2;
    static ArrayList<String> list3;
    static HashMap<Integer, ArrayList<String>> map;

    public static void main(String[] args) {
        // TODO code application logic here

        try {
            FileInputStream fstream = new FileInputStream(Filepath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine, user;
            int lineNumber = 0;

            list1 = new ArrayList<>();
            list2 = new ArrayList<>();
            list3 = new ArrayList<>();
            map = new HashMap<>();

            // Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                process(strLine);
                lineNumber++;
            }
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

        map.put(1, list1);
        map.put(2, list2);
        map.put(3, list3);

        for (int i = 0; i < list1.size(); i++) {
            System.out.println("[Param]");
            System.out.println("param1=" + list1.get(i));
            System.out.println("param2=" + list2.get(i));
            System.out.println("param3=" + list3.get(i));
        }

    }

    public static void process(String str) {

        if (str.contains("param1=")) {
            String[] arr = str.split("param1=");
            ////System.out.println(arr[1].trim());
            list1.add(arr[1].trim());
        } else if (str.contains("param2=")) {
            String[] arr = str.split("param2=");
            //System.out.println(arr[1].trim());
            list2.add(arr[1].trim());
        } else if (str.contains("param3=")) {
            String[] arr = str.split("param3=");
            //System.out.println(arr[1].trim());
            list3.add(arr[1].trim());
        } 
    }     
}

Java代码:

Location

1 个答案:

答案 0 :(得分:1)

您的文本文件似乎是Windows INI文件。 ¿使用Apache Commons Configuration怎么样?具体来说,INIConfiguration类。