文件的操作,都由Context(上下文)對象來衍生
方法 |
說明 |
Context.openFileInput() |
打開應用程序文件讀取。這些文件位於/files子目錄中 |
Context.openFileOutput() |
創建或打開應用程序以供寫入 |
Context.deleteFile() |
通過名稱刪除文件 |
Context.fileList() |
獲取所有/files子目錄下的文件列表 |
Context.getFilesDir() |
獲取應用程序/files子目錄對象 |
Context.getCacheDir() |
獲取應用程序/cache子目錄對象 |
Context.getDir() |
根據名稱創建或 |
表9.2.1 文件Context的重要方法
文件的讀取操作:
FileInputStreamfileIntputStream = openFileInput(fileNameStr);
代碼片段9.2.1 文件讀取操作
註釋:取得文件字符流後,就可以根據不同的文件進行不同的處理。fileNameStr爲文件的文件名。注意讀取文件並不需要指定文件操作權限。
文件的寫入操作:
FileOutputStreamfileOutputStream = openFileOutput(fileNameStr, MODE_PRIVATE);
fileOutputStream.write(str.getBytes("utf-8"));
代碼片段9.2.2 文件寫入操作
註釋:對於文件的寫入操作,則需要指定文件操作權限,不同的操作,會產生不同的效果,這個在前面的9.1節已經描述過。
如果,想要對文件進行復雜操作,那麼上面的兩種方法就無法滿足需求,這個時候要建立複雜文件管理需求,就必須要設置自己的目錄結構。
而要實現這個,就需要使用標準的文件方法java.io.File。
具體實例如下:
File fileDir = getFilesDir();
Log.i("fileDir", fileDir.getAbsolutePath());
String strNewFileName = "myFile.dat";
String strFileContents = "some data for our file";
File newFile = new File(fileDir, strNewFileName);
newFile.createNewFile();
FileOutputStream fo = new
FileOutputStream(newFile.getAbsolutePath());
fo.write(strFileContents.getBytes());
fo.close();
代碼片段9.2.3 普通文件創建
註釋:可以根據自己的需要指定文件夾的位置,上述所寫的getFilesDir方法獲取的是默認的路徑,即data/data/<package name>/files目錄。如果需要更改,可以在創建File的時候,將fileDir的值更改爲你所需要的路徑。
以下是具體例子: