Android文件的读写

存储文件:
 FileOutputStream outStream=this.openFileOutput("zhzhg.txt",Context.MODE_PRIVATE);
 outStream.write("文件的读写",getBytes());
 outStream.close();
读取文件:
 FileInputStream inStream=this.getContext().openFileInput("zhzhg.txt");
 Log.i("FileTest",readInStream(inStream));
 ----------------------------------------------------------------------
 使用绝对路径打开文件:
 File file = new File("/data/data/cn.zhzhg.action/files/zhzhg.txt");
 FileInputStream inStream = new FileInputStream(file);
 Log.i("FileTest", readInStream(inStream));
 注意:上面文件路径中的“cn.zhzhg.action”为应用所在包,当你在编写代码时应替换为你自己应用使用的包。
 ----------------------------------------------------------------------
 读取文件的方:
 public static String readInStream(FileInputStream inStream){
  try {
   ByteArrayOutputStream outStream = new ByteArrayOutputStream();
   byte[] buffer = new byte[1024];
   int length = -1;
   while((length = inStream.read(buffer)) != -1 ){
    outStream.write(buffer, 0, length);
   }
   outStream.close();
   inStream.close();
   return outStream.toString();
  } catch (IOException e){
   Log.i("FileTest", e.getMessage()); 
  }
  return null;
 }
 Activity还提供了getCacheDir()和getFilesDir()方法:
 getCacheDir()方法用于获取/data/data/<package name>/cache目录
 getFilesDir()方法用于获取/data/data/<package name>/files目录

将文件写入SD卡内:
 获取SDCard的状态:Environment.getExtemalStorageState()
  EnvironmentMEDIA_MOUNTED手机装有SDCard,并且可以进行读写
 获取SDCard的目录:Environment.getExtemalStorageDirectory()
     File saveFile=new File("/sdcard/zhzhg.txt");
        或:File sdCardDir=new File("/sdcard");//获取SD卡目录
     File saveFile-new File(sdCardDir,"zhzhg.txt"); 
        FileOutputStream outStream = new FileOutputStream(saveFile);
 outStream.write("文件的读写".getBytes());
 outStream.close();
  注:访问SDCard必须在AndroidManifest.xml中加入访问SDCard的权限 

你可能感兴趣的:(android,String,File,null,buffer,byte)