Android开发5——文件读写

一、基本概念

在Android应用中保存文件,保存的位置有两处

①手机自带的存储空间,较小(如200M),适合保存一些小文件,Android中保存位置在data/data/应用包名/files目录

②外存储设备如SD卡,较大,适合保存大文件如视频,Android中保存位置在mnt/sdcard目录,androd1.5,android1.6保存在sdcard目录

保存的位置通过android的file explorer视图可以找到

二、例子


public class FileService
{
 
 private Context context;

 public FileService(Context context)
 {
  super();
  this.context = context;
 }

 
 @SuppressWarnings("static-access")
 public void save(String filename, String fileContent) throws Exception
 {
  FileOutputStream fos = context.openFileOutput(filename, context.MODE_PRIVATE); // 默认保存在手机自带的存储空间
  fos.write(fileContent.getBytes("UTF-8"));
  fos.close();
 }

 
 public void saveInSDCard(String filename, String fileContent) throws Exception
 {
  // 若文件被保存在SDCard中,该文件不受读写控制
  File file = new File(Environment.getExternalStorageDirectory(), filename);
  FileOutputStream fos = new FileOutputStream(file);
  fos.write(fileContent.getBytes("UTF-8"));
  fos.close();
 }

 
 public String read(String filename) throws Exception
 {
  FileInputStream fis = context.openFileInput(filename); // 默认到手机自带的存储空间去找
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  // 将内容读到buffer中,读到末尾为-1
  while ((len = fis.read(buffer)) != -1)
  {
   // 本例子将每次读到字节数组(buffer变量)内容写到内存缓冲区中,起到保存每次内容的作用
   outStream.write(buffer, 0, len);
  }
  // 取内存中保存的数据
  byte[] data = outStream.toByteArray();
  fis.close();
  String result = new String(data, "UTF-8");
  return result;
 }
}

MainActivity

try
{
 // 存储在手机自带存储空间
 fs.save(filename, fileContent);
 Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT).show();

 // 存储在外部设备SD卡
 // 判断SDCARD是否存在和是否可读写
 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
 {
  fs.saveInSDCard(filename, fileContent);
  Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT).show();
 }
 else
 {
  Toast.makeText(getApplicationContext(), R.string.failsdcard, Toast.LENGTH_SHORT).show();
 }

}
catch (Exception e)
{
 Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_SHORT).show();
 Log.e(tag, e.getMessage());
}

文件名不带路径,直接输入如xy.txt

对于SD卡的操作,需要在AndroidManifest.xml加入权限

 
 

 
 

三、一些API

①Environment.getExternalStorageDirectory()获取的路径为mnt/sdcard目录,对于android1.5,1.6的路径是sdcard目录
②Activity中提供了两个API

getCacheDir()获取的路径为data/data/应用包名/cache目录

getFilesDir()获取的路径为data/data/应用包名/files目录

http://blog.sina.com.cn/s/blog_67aaf44401015vla.html

原文地址:https://www.cnblogs.com/chen110xi/p/3247310.html