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();
    }
}

沒有留言:

發佈留言