1. 程式人生 > >Android:檔案讀寫.

Android:檔案讀寫.

    //往SD卡寫入檔案的方法
    public void savaFileToSD(String filename, String filecontent) throws Exception {
        //如果手機已插入sd卡,且app具有讀寫sd卡的許可權
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            
//這裡就不要用openFileOutput了,那個是往手機記憶體中寫資料的 FileOutputStream output = new FileOutputStream(filename); output.write(filecontent.getBytes()); //將String字串以位元組流的形式寫入到輸出流中 output.close(); //關閉輸出流 } else Toast.makeText(context, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show(); }
//讀取SD卡中檔案的方法 //定義讀取檔案的方法: public String readFromSD(String filename) throws IOException { StringBuilder sb = new StringBuilder(""); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
//開啟檔案輸入流 FileInputStream input = new FileInputStream(filename); byte[] temp = new byte[1024]; int len = 0; //讀取檔案內容: while ((len = input.read(temp)) > 0) { sb.append(new String(temp, 0, len)); } //關閉輸入流 input.close(); } return sb.toString(); }

/*摘自菜鳥教程,侵刪*/

//許可權
<!-- 在SDCard中建立與刪除檔案許可權 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard寫入資料許可權 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>