关于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"/>
然后将文件操作封装在一个类中,在这里我把它命名为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; } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10720.html