转载: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;
- }