1. 程式人生 > >檔案儲存之:File,Cache,Sdcard,三種儲存方式

檔案儲存之:File,Cache,Sdcard,三種儲存方式

//canche儲存資料,記得新增sdcard的讀寫許可權
File file = new File(getCacheDir(), "cache.text");
try {
    FileOutputStream fo = new FileOutputStream(file);
fo.write("這是cache儲存的緩衝資訊".getBytes());
fo.close();
Toast.makeText(MainActivity.this, "儲存成功", 0).show();
} catch (Exception e) {
    e.printStackTrace();
}
//canche讀取資料
File file1 = new File(getCacheDir(), "cache.text"); try { FileInputStream fi = new FileInputStream(file1); BufferedReader br = new BufferedReader( new InputStreamReader(fi)); String readLine = br.readLine(); Toast.makeText(MainActivity.this, readLine, Toast.LENGTH_SHORT).show(); br.close();
fi.close(); } catch (Exception e) { e.printStackTrace(); }
  //File儲存檔案
try {
      FileOutputStream fi = openFileOutput("file.text",
MODE_PRIVATE);
fi.write("這是file格式儲存的檔案".getBytes());
fi.close();
Toast.makeText(MainActivity.this, "儲存成功", 0).show();
} catch (Exception e) {
      e.printStackTrace();
} //FIle讀取檔案 try { FileInputStream fi = openFileInput("file.text"); BufferedReader br = new BufferedReader( new InputStreamReader(fi)); String readLine = br.readLine(); br.close(); fi.close(); Toast.makeText(MainActivity.this, readLine, 0).show(); } catch (Exception e) { e.printStackTrace(); }

        /**
         * Environment.getExternalStorageState()檢測sd卡是否存在
         * Environment.getDataDirectory() 獲取到機身內部儲存的路勁
         *  sdcard 儲存資料
         * 首先判斷SD卡是否存在
         */
if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
//       得到系統路勁
File file = Environment.getExternalStorageDirectory();
String file2 = file.getAbsoluteFile() + "/putsdcard.text";
            try {
                FileOutputStream fo = new FileOutputStream(file2);
fo.write("這是儲存在sdcard上的資料".getBytes());
fo.close();
Toast.makeText(MainActivity.this, "儲存成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
                e.printStackTrace();
}
        }
    }
    //sdcard讀取資料
try {
        File file = new File(Environment.getExternalStorageDirectory(),
"putsdcard.text");
FileInputStream fi = new FileInputStream(file);
BufferedReader br = new BufferedReader(
                new InputStreamReader(fi));
String readLine = br.readLine();
br.close();
fi.close();
Toast.makeText(MainActivity.this, readLine, 0).show();
} catch (Exception e) {
        e.printStackTrace();
}