2014年12月8日 星期一

將 Set 依指定分割符號轉回字串


//  Set<String> 依指定分割符號轉回字串
public static String stringSetToStringWithSplitChar(Set<String> stringSet, String splitChar) throws Exception {
    String returnString = "";
    for (String key : stringSet) {
        if (returnString.length() > 0)
            returnString = returnString + splitChar + key;
        else {
            returnString = key;
        }
    }

    return returnString;
}

字串依分割符號轉為 Set



//將字串依分割符號轉成 Set<String>
public static Set<String> splitToStringSet(String sourceString, String splitChar) throws Exception {
    Set<String> stringSet = new HashSet<String>();
    String[] stringAry = sourceString.split(splitChar);
    for (int i = 0; i < stringAry.length; i++) {
        stringSet.add(stringAry[i]);
    }

    return stringSet;
}

字串陣列轉 Set



//String 陣列 --> Set<String>
public static Set<String> stringArrayToSet(String[] inputArray) throws Exception {
    Set<String> returnSet = new HashSet<String>();
    for (int i = 0; i < inputArray.length; i++) {
        returnSet.add(inputArray[i]);
    }
    return returnSet;
}

2014年12月3日 星期三

JAVA 讀檔並 return List


private static List<String> readFileToStringList(String filePath) {
    List<String> returnList = new ArrayList<String>();
    try {
        FileReader fr = new FileReader(filePath);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            returnList.add(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnList;
}

2014年12月2日 星期二

JAVA 遞迴走訪目錄



private void retrievalFolder(String path) throws Exception {
    try {
        File main = new File(path);
        if (main.isDirectory()) {
            String[] filename = main.list();
            for (int i = 0; i < filename.length; i++) {
                File sub = new File(main.getAbsoluteFile() + File.separator + filename[i]);
                if (sub.isDirectory()) {
                    this.retrievalFolder(main.getAbsoluteFile() + File.separator + filename[i]);
                } else {
                    //TODO
                }
            }
        } else {
            //TODO
        }
    } finally {
        //TODO
    }
}