---
title: "android文件操作的实例"
author: "myclover"
date: "2011-05-15T11:12:23Z"
tags: ["Android", "OS", "XML", "单元测试"]
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2011-05-15T11:12:23Z"
id: 1044562
url: "https://myclover.iteye.com/blog/1044562"
---

第五课，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]