轉載:http://rnmichelle.javaeye.com/blog/923217
本文轉載自本人在javaeye.com 上發表的原創博客,有興趣的朋友可以看看。
Android文件讀寫實例代碼
1.Manifest文件中權限的聲明
爲了能對sdcard進行讀寫操作,即可創建文件或目錄,需要在AndroidManifest.xml中添加權限的聲明:
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.創建目錄及目標文件,並以"utf-8"編碼格式對文件寫入
首先可在目標文件開頭定義一下目錄及文件名常量,方便創建文件時用
- final static String FOLDER = "/sample/";
- final static String FILENAME = "sample";
- final static String SUFFIX = ".txt"; // suffix could be replaced on demand
writeFile函數按命名創建目錄和文件並寫入字串
- private void writeFile(StringBuilder sb) {
- String foldername = Environment.getExternalStorageDirectory().getPath()
- + FOLDER;
- File folder = new File(foldername);
- if (folder != null && !folder.exists()) {
- if (!folder.mkdir() && !folder.isDirectory())
- {
- Log.d(TAG, "Error: make dir failed!");
- return;
- }
- }
- String stringToWrite = sb.toString();
- String targetPath = foldername + FILENAME + SUFFIX;
- File targetFile = new File(targetPath);
- if (targetFile != null) {
- if (targetFile.exists()) {
- targetFile.delete();
- }
- OutputStreamWriter osw;
- try{
- osw = new OutputStreamWriter(
- new FileOutputStream(targetFile),"utf-8");
- try {
- osw.write(stringToWrite);
- osw.flush();
- osw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } catch (UnsupportedEncodingException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (FileNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
注意在new FileOutputStream時用到編碼方式爲"utf-8",即以"utf-8"格式來保存這個,如果想用別的格式來保存,可換成"GB2312","Big5"等。
此外,待寫入的字串可以將字串樣式先用StringBuilder構造好,直接用StringBuilder變量;也可以直接傳入String類型的變量。
3.以"utf-8"解碼格式讀入文
- private String readFile(String filepath) {
- String path = filepath;
- if (null == path) {
- Log.d(TAG, "Error: Invalid file name!");
- return null;
- }
- String filecontent = null;
- File f = new File(path);
- if (f != null && f.exists())
- {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(f);
- } catch (FileNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- Log.d(TAG, "Error: Input File not find!");
- return null;
- }
- CharBuffer cb;
- try {
- cb = CharBuffer.allocate(fis.available());
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- Log.d(TAG, "Error: CharBuffer initial failed!");
- return null;
- }
- InputStreamReader isr;
- try {
- isr = new InputStreamReader(fis, "utf-8");
- try {
- if (cb != null) {
- isr.read(cb);
- }
- filecontent = new String(cb.array());
- isr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- Log.d(TAG, "readFile filecontent = " + filecontent);
- return filecontent;
- }