package tl.android.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.util.Log;
/**
*
* @author amos_tl
* @version 1.0
*
* 实现Android应用程序私有文件或静态资源文件的读取与写入功能.
*
*/
public class FileUtils extends Object{
/**
* LogCat TAG 标识
*/
public static final String TAG = "FileUtils";
/**
* 读取应用程序私有文件.相对路径: /data/data/应用程序包/files/
* @param fileName 想要读取的文件名
* @param buffer 字节方式读取到缓存
* @param context 关联的应用程序上下文
*/
public static void readFile(String fileName, byte[] buffer, Context context){
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
try {
fis.read(buffer);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
} finally{
Log.d(TAG, buffer.length + "bytes ");
}
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
}
}
/**
* 写入应用程序私有文件.相对路径: /data/data/应用程序包/files/
* @param fileName 想要写入的文件名,没有则创建
* @param mode 写入模式
* @param buffer 要写入的字节数组
* @param context 关联的应用程序上下文
*/
public static void writeFile(String fileName, int mode, byte[] buffer, Context context){
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, mode);
try {
fos.write(buffer);
fos.flush();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}finally{
Log.d(TAG, buffer.length + "bytes");
}
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
}
}
/**
* 读取应用程序静态资源文件
* @param id 资源文件ID
* @param buffer 字节方式读取到缓存
* @param context 关联的应用程序上下文
*/
public static void readRawFile(int id, byte[] buffer, Context context){
InputStream is = null;
try{
is = context.getResources().openRawResource(id);
is.read(buffer);
}catch(Exception e){
Log.e(TAG, e.getMessage(), e);
}finally{
Log.d(TAG, buffer.length + "bytes ");
}
}
}