應用私有存儲文件的寫入與讀取 - openFileInput 和 openFileOutput
應用私有存儲文件:
/data/data/<package name>/files/目錄下
應用刪除時,即清空該目錄。
//通過context對象獲取私有目錄:/data/data/packagename/files
context.getFileDir().getPath()
Context對象中文操作的API及說明
方法名 | 說明 |
openFileInput(String filename) | 打開應用程序私有目錄下的的指定私有文件以讀入數據,返回一個FileInputStream 對象 |
openFileOutput(String filename, 操作模式) | 打開應用程序私有目錄下的的指定私有文件以寫入數據,返回一個FileOutputStream 對象, 如果文件不存在就創建這個文件。 |
fileList() | 搜索應用程序私有文件夾下的私有文件,返回所有文件名的String數組 |
deleteFile(String fileName) | 刪除指定文件名的文件,成功返回true,失敗返回false |
filename :不能包含路徑分隔符“/” ,如果文件不存在,Android會自動創建它。創建的文件保存在/data/data/<package name>/files目錄
在使用openFileOutput方法打開文件以寫入數據時,需要指定打開模式。默認為零,即MODE_PRIVATE。不同的模式對應的的含義如下:
openFileOutput方法打開文件時的模式:
常量 | 含義 |
MODE_PRIVATE | 默認模式,文件只可以被調用該方法的應用程序訪問 |
MODE_APPEND | 如果文件已存在就向該文件的末尾繼續寫入數據,而不是覆蓋原來的數據。 |
MODE_WORLD_READABLE | 賦予所有的應用程序對該文件讀的權限。 |
MODE_WORLD_WRITEABLE | 賦予所有的應用程序對該文件寫的權限。 |
e.g.
1 package com.fileoperate; 2 3 4 import java.io.FileInputStream; 5 6 import java.io.FileOutputStream; 7 8 import android.app.Activity; 9 10 import android.graphics.Color; 11 12 import android.os.Bundle; 13 14 import android.widget.TextView; 15 16 17 public class FileOperationActivity extends Activity{ 18 19 //文件名稱 21 String fileName = "test.txt"; 22 23 //寫入和讀出的數據信息 24 String content = "demo"; 25 26 TextView tv_content; 27 28 @Override 30 protected void onCreate(Bundle savedInstanceState) { 31 32 super.onCreate(savedInstanceState); 33 34 setContentView(R.layout.main); 35 36 writeFileData(fileName, content); // 寫入文件 37 38 String result = readFileData(fileName); // 讀取文件 39 40 tv_content = (TextView) findViewById(R.id.tv_content); 41 42 tv_content.setText(result); 43 } 44 45 //向指定的文件中寫入指定的數據 47 public void writeFileData(String filename, String content){ 48 49 try { 50 51 FileOutputStream fos = this.openFileOutput(filename, MODE_PRIVATE);//獲得FileOutputStream 52 53 //將要寫入的字符串轉換為byte數組 54 55 byte[] bytes = content.getBytes(); 56 57 fos.write(bytes);//將byte數組寫入文件 58 59 fos.close();//關閉文件輸出流 60 61 } catch (Exception e) { 63 e.printStackTrace(); 65 } 67 } 70 71 //打開指定文件,讀取其數據,返回字符串對象 73 public String readFileData(String fileName){ 74 75 String result=""; 76 77 try{ 78 79 FileInputStream fis = thisopenFileInput(fileName); 80 81 //獲取文件長度 83 int lenght = fis.available(); 84 85 byte[] buffer = new byte[lenght]; 86 87 fis.read(buffer); 88 89 //將byte數組轉換成指定格式的字符串 91 result = new String(buffer, "UTF-8"); 92 93 } catch (Exception e) { 95 e.printStackTrace(); 97 } 98 99 return result; 101 } 103 }
SD card 文件 讀寫
FileInputStream
讀取文件內容:
1 public static String read(String fileName) { 2 3 FileInputStream fis = null; 4 String result = null; 5 6 try { 7 8 File file = new File(Environment.getExternalStorageDirectory(), fileName + ".txt"); 9 10 fis = new FileInputStream(file); 11 12 byte[] buffer = new byte[fis.available()]; 13 fis.read(buffer); 14 fis.close(); 15 16 result = new String(buffer, "UTF-8"); 17 18 } catch (Exception ex) { 19 20 ex.printStackTrace(); 21 22 try { 23 if (fis != null) { 24 fis.close(); 25 } 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 } 30 31 return result; 32 }
BufferReader
讀取文件
1 try { 2 File file = new File(Environment.getExternalStorageDirectory(), 3 DEFAULT_FILENAME); 4 BufferedReader br = new BufferedReader(new FileReader(file)); 5 String readline = ""; 6 StringBuffer sb = new StringBuffer(); 7 while ((readline = br.readLine()) != null) { 8 System.out.println("readline:" + readline); 9 sb.append(readline); 10 } 11 br.close(); 12 System.out.println("讀取成功:" + sb.toString()); 13 } catch (Exception e) { 14 e.printStackTrace(); 15 }
FileOutputStream
寫入文件內容:覆蓋原本內容(先清空原有內容,再寫入)
1 /* 2 * 定義文件保存的方法,寫入到文件中,所以是輸出流 3 * */ 4 public static void save(String fileName, String content) { 5 FileOutputStream fos = null; 6 try { 7 8 /* 判斷sd的外部設置狀態是否可以讀寫 */ 9 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 10 11 File file = new File(Environment.getExternalStorageDirectory(), fileName + ".txt"); 12 13 // 先清空內容再寫入 14 fos = new FileOutputStream(file); 15 16 byte[] buffer = content.getBytes(); 17 fos.write(buffer); 18 fos.close(); 19 } 20 21 } catch (Exception ex) { 22 23 ex.printStackTrace(); 24 25 try { 26 if (fos != null) { 27 fos.close(); 28 } 29 } catch (Exception e) { 30 e.printStackTrace(); 31 } 32 } 33 }
RandomAccessFile:
追加內容:在原有的內容基礎上追加內容
1 public static void write(String content) { 2 try { 3 //判斷實際是否有SD卡,且應用程序是否有讀寫SD卡的能力,有則返回true 4 if (Environment.getExternalStorageState().equals( 5 Environment.MEDIA_MOUNTED)) { 6 // 獲取SD卡的目錄 7 File sdCardDir = Environment.getExternalStorageDirectory(); 8 String path = "/test/"; 9 File dir = new File(sdCardDir + path); 10 if (!dir.exists()) { 11 dir.mkdirs(); 12 } 13 File targetFile = new File(sdCardDir.getCanonicalPath() + path+"aaa.txt"); 14 //使用RandomAccessFile是在原有的文件基礎之上追加內容, 15 //而使用outputstream則是要先清空內容再寫入 16 RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); 17 //光標移到原始文件最后,再執行寫入 18 raf.seek(targetFile.length()); 19 raf.write(content.getBytes()); 20 raf.close(); 21 } 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 }
BufferedWriter
Writer類就是為寫文本而設計的。使用BufferedWriter寫入文本時不需要將文本轉換成字節數組.
這里有一個 "修飾類 "的概念
FileWriter 是被修飾者
BufferedWriter 是修飾者
一般用法為
BufferedWriter bw = new BufferedWriter(new FileWriter("filename"));
上面這個加了一個緩沖,緩沖寫滿后在將數據寫入硬盤
這樣做極大的提高了性能
如果單獨使用 FileWriter 也可以
你每寫一個數據,硬盤就有一個寫動作,性能極差
1 try { 2 3 File file = new File(Environment.getExternalStorageDirectory(), 4 DEFAULT_FILENAME); 6 /** 7 * 為了提高寫入的效率,使用了字符流的緩沖區。 8 * 創建了一個字符寫入流的緩沖區對象,並和指定要被緩沖的流對象相關聯。 9 */ 10 //第二個參數意義是說是否以append方式添加內容 11 BufferedWriter bw = new BufferedWriter(new FileWriter(file, true)); 12 13 //使用緩沖區中的方法將數據寫入到緩沖區中。 14 bw.write("hello world !"); 15 bw.newLine(); 16 bw.newLine(); 17 bw.write("test"); 18 bw.write("content"); 19 //使用緩沖區中的方法,將數據刷新到目的地文件中去。 20 bw.flush(); 21 //關閉緩沖區,同時關閉了FileWriter流對象 22 bw.close(); 23 System.out.println("寫入成功"); 24 25 } catch (Exception e) { 26 e.printStackTrace(); 27 }
/data/data: context.getFileDir().getPath();
是一個應用程序的私有目錄,只有當前應用程序有權限訪問讀寫,其他應用無權限訪問。一些安全性要求比較高的數據存放在該目錄,一般用來存放size比較小的數據。
/sdcard: Enviroment.getExternalStorageDirectory().getPath();
是一個外部存儲目錄,只用應用聲明了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>的一個權限,就可以訪問讀寫sdcard目錄;所以一般用來存放一些安全性不高的數據,文件size比較大的數據。