1. 程式人生 > >Android手機SD卡建立檔案並寫入內容

Android手機SD卡建立檔案並寫入內容

在Android開發過程中,經常需要在手機中寫入並存儲一些檔案,下面是寫入檔案程式碼部分,帶註釋可直接使用。

/**
     * 寫入檔案方法
     * @param content
     */
    public static void write(String content) {
        try {
            //判斷實際是否有SD卡,且應用程式是否有讀寫SD卡的能力,有則返回true
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 獲取SD卡的目錄
File sdCardDir = Environment.getExternalStorageDirectory(); String path = "/AAA/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } File targetFile = new File(sdCardDir.getCanonicalPath() + path+"aaa.txt"
); //使用RandomAccessFile是在原有的檔案基礎之上追加內容, //而使用outputstream則是要先清空內容再寫入 RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); //游標移到原始檔案最後,再執行寫入 raf.seek(targetFile.length()); raf.write(content.getBytes()); raf.close(); } } catch
(Exception e) { e.printStackTrace(); } }