拆分字符串并保存到对象列表

时间:2014-01-27 03:01:01

标签: java string arraylist stringtokenizer

我有一个String,我想从Stringbuffer中拆分并将其保存到对象的arraylist中。

我有一串看起来像这样的数据:

001>10102011>874837>Y>Y>TEST001>No\\002>11102011>8743834>Y>Y>null>No\\ 

\将表示保存到新对象。 如何将此字符串保存到List listsaveobj?

我的示例保存对象是

public class SaveObject{
    private String obj1;
    private String obj2;
    private String obj3;
    private String obj4;
    private String obj5;
    private String obj6;
    private String obj7;

    //getters and setters
}

我被困在

    StringTokenizer st= new StringTokenizer(sb1.toString(),"\\\\");
        int count = 0;
        int total= st.countTokens();//count no of rows of data
        System.out.println(total);

        while(count<total){
            while(st.hasMoreElements()){
                tmpList.add(st.nextToken());
                count++;
            }
        }

              System.out.println(tmpList.size());

        for(int j = 0; j<tmpList.size(); j++){
            String str = tmpList.get(j);

            StringTokenizer st2 = new StringTokenizer(str, ">");
            while (st2.hasMoreElements()){

                System.out.println(st2.nextToken());
                            // is it possible to save into ArrayList of objects here?
                            // I can see that the String can split into
                           // 001
                           // 10102011
                           // 874873
                           // Y
                           // Y
                           // TEST001
                           // No etc
                           /* using st.nextToken but I don't know how to continue from here. Pls help!! Thanks. I want to do something like
                          obj = new Object();
                          obj.saveObj1(...);
                          obj.saveObj2(...);
                          obj.saveObj3(...);
                          obj.saveObj4(...);
                          obj.saveObj5(...);
                          obj.saveObj6(...);
                          obj.saveObj7(...);
                          listsaveobj.add(obj); but it's not possible? */
                     }
        }

1 个答案:

答案 0 :(得分:1)

以下是提取数据的更好方法:

String s = "001>10102011>874837>Y>Y>TEST001>No\\\\002>11102011>8743834>Y>Y>null>No\\\\";
String[] rows = s.split("\\\\");
for (String r : rows) {
    String[] cols = r.split(">");
    for (String c : cols) {
        System.out.print(c + "\t");
    }
    System.out.println();
}