Android 文件讀寫
關于Android文件的讀寫有兩種方式
一種是將txt文件當成資源文件放在res/raw或則res/asset文件夾下,raw的文件可以通過R.raw.fileName獲得,asset下的文件可以通過AssetManager am = getAssets();am.open(“FileName”);來打開文件。但是如果把文件當成資源文件存放的話,只能讀不能寫。如果要想寫入數據的話,就使用第二種方法
第二種方法從sd卡中讀寫文件,這樣首先要向AndroidManifest.xml中加入兩條權限消息
<!-- 在SDCard中創建與刪除文件權限 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往SDCard寫入數據權限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> </pre>
然后將文件操作封裝在一個類中,在這里我把它命名為FileOption,先將代碼粘貼如下:package com.example.littleapplication;import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.util.Vector; import android.os.Environment; import android.util.Log; public class FileOption { private String fileName; private File targetFile; private File sdCardDir; public FileOption(String fileName) throws IOException { // TODO Auto-generated constructor stub boolean mark = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); if(mark) { this.fileName = fileName; this.sdCardDir = Environment.getExternalStorageDirectory(); this.targetFile = new File(this.sdCardDir.getCanonicalPath()+this.fileName); if(this.targetFile.exists()==false) { this.targetFile.createNewFile(); } } else{ Log.e("SDK", "無內存卡"); } } public Vector read() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(this.sdCardDir.getCanonicalPath()+this.fileName); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); Vector res = new Vector(); String line = null; while((line = br.readLine())!=null) { res.add(line); } br.close(); return res; // TODO Auto-generated method stub } public boolean write(String add) throws IOException { RandomAccessFile raf = new RandomAccessFile(this.targetFile,"rw"); raf.seek(targetFile.length()); //換行 raf.write(add.getBytes()); raf.writeChar('\n'); raf.close(); return true; } /**返回一共有多少條記錄 * @throws IOException * @throws FileNotFoundException */ public int size() throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(this.sdCardDir.getCanonicalPath()+this.fileName); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = null; int count = 0; while((line = br.readLine())!=null) { count++; } //每三行代表一個數據項 //分別是 id title content data level return count/5; } } </pre>
本文由用戶 cc68 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!