●補充說明和程式說明---檔案存取

(一)在做檔案存取時
1.在本機下的data/data/packagename這個資料夾,會在install的時候產生,移除的時候刪除,這個資料夾下的所有內容可以不受限制任意存取
2.android 6以前,sdcard/data/packagename下的資料夾,跟上面一樣, 會在install的時候產生,移除的時候刪除,這個資料夾下的所有內容可以不受限制任意存取
3. android 6以後,sdcard下的資料夾只要app被授權,就可以任意存取sd卡中的內容
 
(二)android寫入
public void clickwrite(View view) {
 
String fname=getFilesDir().getAbsolutePath();
try {
FileWriter fw=new FileWriter(fname+ File.separator+"data.txt");
fw.write("android is fun");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
**說明:
1. getFilesDir()和getCacheDir(),兩個不同資料夾(File和Cache),file放重要的資料,cache放暫時使用的資料,在手機設定裡面的app中,有兩個按鈕,clear data是清除file中的內容,clear cache是清除cache中的內容
2.用 getFilesDir().getAbsolutePath(); 取得內部儲存空間file資料夾名稱和絕對路徑位置
3.建立一個寫入資料的物件,寫入的資料檔案路徑和名稱為 fname+ File.separator+"data.txt"=> File.separator是分隔線, data.txt  是檔名
4.fw.write(寫入的內容)
 
設定/app/專案名稱
fileWriter and fileReader
完成後可以看到檔案成功寫入,可以匯出桌面看內容
fileWriter and fileReader
 
(三)android讀取
public void clickread(View view) throws FileNotFoundException {
    char [] ch=new char[100];
    String fname=getFilesDir().getAbsolutePath();
    try {
        FileReader fr=new FileReader(fname+File.separator+"data.txt");
        fr.read(ch);
        String str=new String(ch);
        Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
    }catch (FileNotFoundException e){
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
**說明:
1.因為 FileReader讀進來的是一個char array,所以要先建一個char array來儲存之
2.一樣要先抓到要讀取的檔案
3.read()=>int read (byte[] b) :Reads some number of bytes from the input stream and stores them into the buffer array b.
4. String str=new String(ch);=>把ch轉成String
=>在String類別中有一個建構式:String(char[] value)
=>Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
 

 

 

●程式參考(GitHub):使用FileWriter和FileReader做檔案(File)的讀取與寫入

arrow
arrow
    全站熱搜

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