File的使用

數據的存儲有多種方式,比如數據庫存儲、SharedPreferences存儲、文件存儲等;


1. 基本使用

文件存儲

**/storage/emulated/0/ 某某文件夾 : 0代表的是設備內存,1代表的是內存卡,
直接在內部儲存裏找 /0/ 後面那個某某文件夾,就可以找到。
/storage/emulated/0/Android/data/com.lzz.test/cache/files**

(1)FileOutputStream out = context.openFileOutput(String filename,int mode); 以mode模式獲得文件輸出流
(2)out.write(byte[]b);

FileOutputStream out = null;  
out = context.openFileOutput(filename, Context.MODE_***);  
out.write(filecontent.getBytes("UTF-8"));  
out.close(); 

注意:文件默認會存儲到/data/data/package/files中;

文件讀取

(1)FileInputStream in = context.openFileInput(String filename); 獲得某個文件的文件流
(2)int length = in.read(byte[]);

//每次讀取固定的字節,並將此字節輸出到字節輸出流中,當全部讀取完畢後,將字節流中的內容一併輸出 
FileInputStream in = null;
ByteArrayOutputStream bout = null;  
byte[]buf = new byte[1024]; 
bout = new ByteArrayOutputStream(); 
int length = 0;  
in = context.openFileInput(filename); //獲得輸入流  
while((length=in.read(buf))!=-1){  
    bout.write(buf,0,length);  
} 
byte[] content = bout.toByteArray();  
filecontentEt.setText(new String(content,"UTF-8")); //設置文本框爲讀取的內容  
in.close();  
bout.close(); 

注意:默認會讀取/data/data/package/files的文件;


2. 文件模式

1.Context.MODE_PRIVATE:私有覆蓋模式
- rw- rw- —
只能被當前應用訪問,並且如果寫入,則覆蓋;

2.Context.MODE_APPEND:私有追加模式
- rw- rw- —
只能被當前應用訪問,並且如果寫入,則追加;

3.Context,MODE_WORLD_READABLE:公有隻讀模式 - rw- rw- r–
可以被其他應用讀取;

4.Context.MODE_WORLD_WRITEABLE:公有可寫模式 - rw- rw- -w-
可以被其他應用寫入,但不能讀取;

*注意,如果希望其他使得文件模式疊加,則可以使用加號連接;
比如:Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE 表示其他應用讀寫;


3. 簡單使用

/**  /data/data/package/files     */
public class MainActivity extends Activity { 

    private String filecontent = "This is content----.";
    private String filename = "title.txt";
    private Button saveButton,readButton;  
    private Context context = this;  

    private OnClickListener listener = new OnClickListener(){  
        @Override  
        public void onClick(View v) {  
            if(v==saveButton){  
                FileOutputStream out = null;  
                try {  
                    out = context.openFileOutput(filename, Context.MODE_PRIVATE);  
                    out.write(filecontent.getBytes("UTF-8"));  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                finally{  
                    try {  
                        out.close();  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
            else if(v==readButton){  
                FileInputStream in = null;  
                ByteArrayOutputStream bout = null;  
                byte[]buf = new byte[1024];  
                bout = new ByteArrayOutputStream();  
                int length = 0;  
                try {  
                    in = context.openFileInput(filename); //獲得輸入流  
                    while((length=in.read(buf))!=-1){  
                        bout.write(buf,0,length);  
                    }  
                    byte[] content = bout.toByteArray();  
                    Log.i("lzz",new String(content,"UTF-8")); //設置文本框爲讀取的內容  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                //filecontentEt.invalidate(); //刷新屏幕  
                try{  
                    in.close();  
                    bout.close();  
                }  
                catch(Exception e){}  
            }  
        }  

    };  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        saveButton = (Button)this.findViewById(R.id.saveButton);  
        readButton = (Button)this.findViewById(R.id.readButton);  
        saveButton.setOnClickListener(listener);  
        readButton.setOnClickListener(listener);  
    }  
} 

保存在SD卡中

通常情況下多數應用程序都會將緩存的位置選擇爲 /sdcard/Android/data//cache 這個路徑。
選擇在這個位置有兩點好處:
第一,這是存儲在SD卡上的,因此即使緩存再多的數據也不會對手機的內置存儲空間有任何影響只要SD卡空間足夠就行。
第二,這個路徑被Android系統認定爲應用程序的緩存路徑,當程序被卸載的時候,這裏的數據也會一起被清除掉,這樣就不會出現刪除程序之後手機上還有很多殘留數據的問題。
假如沒有此目錄時,可以用以下

//路徑例如: /SD卡/Android/data/程序的包名/cache/uniqueName
private static File getDiskCacheDir(Context context, String uniqueName) {
    String cachePath;
    if (Environment.MEDIA_MOUNTED.equals(Environment
            .getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
        cachePath = context.getExternalCacheDir().getPath();
    } else {
        cachePath = context.getCacheDir().getPath();
    }
    return new File(cachePath + File.separator + uniqueName);
}

設置權限

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>  

存儲到sdcard核心代碼:

    File f = new File(Environment.getExternalStorageDirectory(),filename);  
    out = new FileOutputStream(f,true);  
    out.write(filecontent.getBytes("UTF-8"));  

/storage/emulated/0/title.txt

讀取sdcard核心代碼:

    File f = new File(Environment.getExternalStorageDirectory(),filename);  
    in = new FileInputStream(f);  
    while((length=in.read(buf))!=-1){  
        bout.write(buf,0,length);  
    }  
    byte[] content = bout.toByteArray();  
發佈了79 篇原創文章 · 獲贊 34 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章