ITeye博客

android文件操作的实例

myclover · 2011-05-15 11:12 · android · 移动开发 · OS · XML · Android · 单元测试 · Markdown

第五课,android文件操作的实例,主要对SDcard的读写操作。 [code] package com.myclover.file.service; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import android.content.Context; import android.os.Environment; public class FileOperateService { private Context context; public FileOperateService(Context context) { this.context = context; } /** * 功能描述: * 文件保存的方法 * @param fileName 文件名 * @param content 文件的内容 * @param mode 文件的模式 如果为-1时,表示的是保存到SDcard卡上,否则就是保存到应用目录中 * @throws Exception */ public void saveFile(String fileName , String content , int mode) throws Exception { FileOutputStream fouts = null; //文件保存到应用的目录下 if(mode != -1) { //如果保存在应用中,则直接使用openFileOutput即可打开应用中的文件 fouts = context.openFileOutput(fileName, mode); } else { //文件保存到SDcard卡上 //Environment.getExternalStorageDirectory()表示取得SDcard的路径,相当于"/sdcard/" File file = new File(Environment.getExternalStorageDirectory() , fileName); fouts = new FileOutputStream(file); } fouts.write(content.getBytes()); fouts.close(); } /** * 功能描述: * 读取文件内容 * @param fileName 文件名 * @param isSdcard 是否读取sdcard,为true时表示取得的是SDCard的文件内容 * @return 返回值:返回文件内容 * @throws Exception */ public String readFile(String fileName , boolean isSdcard)throws Exception { FileInputStream fins = null; if(isSdcard) { File file = new File(Environment.getExternalStorageDirectory() , fileName); fins = new FileInputStream(file); } else { fins = context.openFileInput(fileName); } ByteArrayOutputStream bouts = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int len = 0; while((len = fins.read(buf)) != -1) { bouts.write(buf, 0, len); } byte[] data = bouts.toByteArray(); fins.close(); bouts.close(); return new String(data); } } [/code] [code] [/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。