顯示包含「java」標籤的文章。顯示所有文章
顯示包含「java」標籤的文章。顯示所有文章

2011/12/14

java replaceAll with $

as $ is one of the symbol used in regular expression
it will fail at replpace all


solution

replace all $ to \\$
String a = "$38 Apple";
a = a.replaceAll("\\$", "\\\\\\$");

replace
String b = "testing testing REPLACE_ME testing testing";
String finalStr= start.replaceAll("REPLACE_ME", a);

2011/03/18

java write to file

點樣可以將d string output 做一個file 呢~?

其實好簡單的~

有幾個方法都得
咁我就用左其中一個la

//filePath: 目標file 的path e.g: /logs/example/output.txt
//str: 要寫落file 的text
public static void writeToFile(String filePath, String str){
    try {     
        // 開個file, 如果冇呢個file, 就會自動create
        FileOutputStream outFile = new FileOutputStream(filePath);

        // 寫string 落個file, 但要轉做bytes 先
        outFile.write(sb.toString().getBytes("UTF-8"));

         // 以防d bytes 未寫好, 要flush 一下
        outFile.flush();

         //  寫完後 close 個file =], 完
        outFile.close();

    } catch (IOException e){
        e.printStackTrace();
    }
}