close

注意:此份code為筆記,尚未實際跑過,不保證跑得出來或無錯字

寫入SD:
1.取得SD檔案路徑
File 物件 = new File(Environment.getExternalStrogeDirectory(),檔名);
例如:
File filaname = new File(Environment.getExternalStorageDirectory(),"login.txt")
2.建立FileOutputStream物件以便將資料寫入檔案
FileOutputStream 物件 = new FileOutputStream(SD檔案路徑)
例如:
FileOutputStream fout = new FileOutputStream(filename);
3.使用 FileOutputStream 的 write 物件
FileOutputStream 變數.write(字串.getBytes());
例如:
fout.write("i love you!!".getBytes());  //寫入的資料必須是Byte型式
4.用FileOutputStream物件關閉檔案
fout.close();


總結:得到檔案路徑(File物件)後,使用FileOutputStream物件操控檔案操作

讀取SD卡資料:
1.
File filename = new File(Evironment.getExternalStrogeDirectory(),"login.txt");
2.
FileInputStream fin = new FileInputStream(filename);
3.為了提升讀寫效率,使用BufferedReader物件對檔案進行讀取
BufferedReader reader = new BufferReader(new InputStreamReader(fin));
4.讀取一行資料
sString str = reader.readLine();
5.關閉
reader.close();
fin.close();

總結:使用buffer可加快執行速度

設定存取SD權限
---------------------------------------------------------------------------------
將資料寫入已或未存在檔案之中:
FileOutputStream 物件 = openFileOutput(檔名,權限); 
BufferedOutputStream 物件 = new BufferedOutputStream(FileOutputStream物件);
BufferedOutputStteam 變數.write(字串.getBytes());
例如:
FileOutputStream fout = openFileOutput("test.txt",MODE_PRIVATE); //只有本應用程式可以存取,如果檔案存在則覆蓋
BufferedOutputStream buffout = new BufferedOutputStream(fout);
buffout.write("i love you!!".getBytes());
buffout.close();

總結:
try{
    FileOutputStream fout = openFileOutput("test.txt",MODE_PRIVATE); //只有本應用程式可以存取,如果檔案存在則覆蓋
    BufferedOutputStream buffout = new BufferedOutputStream(fout);
    buffout.write("i love you!!".getBytes());
    buffout.close();
}catch(Exception e){
    e,printStackTrace();
}

讀取:
 

引用:android初學特訓班

arrow
arrow
    全站熱搜

    KR 發表在 痞客邦 留言(0) 人氣()