分享

16. 文件的保存与读取

 黎可图书馆 2014-07-11
一. 概述
此例子将文本文件存入data/data/files中,只有本程序能够读取。

二. 实现
1. 保存文件
/** * Save content to a file 
 * @param fileName the name of the file 
 * @param fileContent the content of the file 
 * @throws IOException 
 */ 
 public void save(String fileName, String fileContent) throws IOException { 
 FileOutputStream out = context.openFileOutput(fileName, 
Context.MODE_APPEND); 
 out.write(fileContent.getBytes()); 
 out.flush(); 
 out.close(); 
 }

2. 读取文件
/** * read the content in data/data/com.like.app/files 
 * @param fileName the name of the file 
 * @param fileContent the content of the file 
 * @return return the content of the file 
 * @throws IOException 
 */ 
 public String read(String fileName, String fileContent) throws IOException { 
 FileInputStream inputStream = context.openFileInput(fileName); 
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
 byte[] buffer = new byte[1024]; 
 int len = 0; 
 while((len = inputStream.read(buffer)) != -1) { 
 outputStream.write(buffer, 0, len); 
 } 
 byte[] data = outputStream.toByteArray(); 
 outputStream.close();
 inputStream.close();
 return new String(data);
 }

3. 保存文件至SD卡
(1) 在操作SD卡之前,需要加入权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

(2) 方法实现
/** * save file to sdcard 
 * @param fileName the name of the file 
 * @param fileContent the content of the file 
 * @throws IOException 
 */ 
 public void saveToSdcard(String fileName, String fileContent) throws IOException {
 //getExtrnalStorageDirectory() 获取sdcard路径 
 File file = new File(Environment.getExternalStorageDirectory(), fileName); 
 FileOutputStream outputStream = new FileOutputStream(file); 
 outputStream.write(fileContent.getBytes()); outputStream.close();
 }

4. 从SD卡读取文件
/** * read content from sdcard 
 * @param fileName the name of the file 
 * @param fileContent the content of the file 
 * @return return the content of the file 
 * @throws IOException 
 */ 
 public String readFromSdcard(String fileName, String fileContent) 
throws IOException { 
 FileInputStream inputStream = new FileInputStream(
new File(Environment.getExternalStorageDirectory(), fileName)); 
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
 byte[] buffer = new byte[1024]; 
 int len = 0; while((len = inputStream.read(buffer)) != -1) { 
 outputStream.write(buffer, 0, len);
 } 
 byte[] data = outputStream.toByteArray(); 
 outputStream.close(); 
 inputStream.close(); 
 return new String(data); 
 }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约