1、保存文件
public FileService(Context context){
//初始化context
this.context = context;
}
/*文件存储
* */
public void save(String filename, String filecontent) throws Exception {
FileOutputStream outputStream = context.openFileOutput(filename,context.MODE_PRIVATE);
//把输出流转化成二进制
outputStream.write(filecontent.getBytes());
//关闭输出流
outputStream.close();
}
2、读取文件
/*
**文件读取
*/
public String read(String filename) throws Exception {
FileInputStream inputStream = context.openFileInput(filename);
//把读入的数据存入到内存中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//把读入的数据都存入到buffer数组中
byte[] buffer = new byte[1024];
int len = 0;
//把输入流中的数据读入到一个字节数组中,当数据一次读入超过1024字节时就进行循环,重复把存入数组中的数据不断地写进内存
while((len = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,len);
}
//读取内存的所有数据
byte[] data = outputStream.toByteArray();
//把从内存中获取到数据转化成字符串,关闭流,然后返回即可
String result = new String(data);
outputStream.close();
inputStream.close();
return result;
}
3、把文件存入SDCard中
public void saveSDCard(String filename,String filecontent) throws Exception {
//找到sdcard的目录
File file = new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream stream = new FileOutputStream(file);
stream.write(filecontent.getBytes());
stream.close();
}
在Mainfest.xml中声明权限为:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> //表示在SDCard中创建与删除文件权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> //表示往SDCard中写入数据的权限
核心代码如下所示:
//把文件写入到SD卡中
try {
//判断SDCard是否存在,并且可以读写
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
savesuccess.saveSDCard(filename,filecontent);
Toast.makeText(getApplicationContext(),R.string.saveuccess,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),R.string.error,Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),R.string.savefail,Toast.LENGTH_LONG).show();
}
}