Monday, July 18, 2011

[java] Java string split(字串切割)

這次我需要讀取網路上的某個.txt檔案,而檔案的內容長得像這樣:
001:1097
002:92
006:392
008:282
009:85
010:79
011:71
045:814
048:193


我需要分行讀取之後分別將冒號左邊跟右邊的數字加入map裡面,最後再把map通通丟進去一個List。

我知道利用readLine可以把每行字丟進去List容器裡面,但是想了很久不知道該怎麼分別讀取冒號左邊跟右邊的數字,經由好朋友的提示,我才想起來有split可以使用。用split就可以很輕鬆的解決我的需求,節錄部分程式碼如下:

//首先new一個items ArrayList容器物件,等一下拿來裝map用的
private ArrayList〈HashMap〈String, String〉〉 items= new ArrayList〈HashMap〈String, String〉〉();
private final static String TXT_PATH = "http://aaa.bbb.ccc.com.tw/all.txt";
public static int IO_BUFFER_SIZE = 1024;

//再來寫一個method,此method會回傳我需要的字串物件

    public String check(String id){
        String name = null;
        try{
            HashMap
String, String map = null; 
            InputStream ins = new BufferedInputStream(new URL(TXT_PATH).openStream(), IO_BUFFER_SIZE);
            BufferedReader br = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                map = new HashMap
String, String();
                String[] token = inputLine.split(":");//利用":"做字串分割
                map.put("no", token[0]);//將String[0] 陣列放進去map裡面
                map.put("space", token[1]);
//將String[1] 陣列放進去map裡面
                items.add(map);//將兩個map丟進item List容器裡面
            }
        }catch(Exception e){
           
        }
       
        for(int i = 0;i
〈 items.size(); i++){
            Map〈String, String〉 detail = items.get(i);
            String title = detail.get("no");
            if( id.equals(title)){
                name = detail.get("space");
            }
        }
        return name;
    }

0 comments:

Post a Comment