打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
16. 文件的保存与读取
一. 概述
此例子将文本文件存入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); 
 }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
文件的保存与读取
java上传文件跟批量下载文件
java 从网络Url中下载文件
Java文件操作详解
文件上传流式处理commons
java之通过FileChannel实现文件复制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服