//寫檔範例
ublic void writeDataToSD(){
try{
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
/* 判斷外部裝置是否可以讀寫 */
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
/* 輸出資料緩衝區*/
FileOutputStream fos = new FileOutputStream(file);
/* 寫入的資料*/
String message = "Test";
/* 將資料轉成byte 模式*/
byte[] buffer = message.getBytes();
/* 寫入資料*/
fos.write(buffer);
/* 關閉緩衝*/
fos.close();
Toast.makeText(MainActivity.this, "檔案寫入成功", 1000).show();
}
}catch(Exception ex){
Toast.makeText(MainActivity.this, "檔案寫入失败", 1000).show();
}
//讀檔範例
public void readDataFromSD(){
try{
/* 設定檔案*/
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
/* 輸入資料緩衝區 */
FileInputStream fis = new FileInputStream(file);
/* 準備一個byte biffer用來存讀入的資料*/
byte[] buffer = new byte[fis.available()];
/* 讀取資料*/
fis.read(buffer);
/* 關閉緩衝 */
fis.close();
/* 將資料轉成UTF-8格式*/
String res = EncodingUtils.getString(buffer, "UTF-8");
Toast.makeText(MainActivity.this, "檔案讀取成功,data:"+res, 1000).show();
}catch(Exception ex){
Toast.makeText(MainActivity.this, "檔案讀取失败!", 1000).show();
}
}
visited 13 states (5.77%)
Create your own visited map of The World or Triposo world travel guide for Android
2014-09-25
Android應用程式讀寫SD上的檔案
檔案讀寫的方式有很多種,這邊放了兩個函式範例可以測試讀寫SD卡上的檔案。
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言