Android文件访问

Android中对于文件操作除了java的基础库汇总的IO、File等之外,还提供了几种API

1、Context类提供的openFileOutput()和openFileInput()两个方法分别获取IO流,然后就可以进行相关读写操作了。
  写操作中有个文件的操作模式的参数,也是Context提供的几个常量:MODE_PRIVATE,覆盖文件,默认模式;
  MODE_APPEND,追加内容,不存在就新建。
  //读取文件
public String load(Context context,String fileName) { FileInputStream is=null; BufferedReader reader=null; StringBuilder result=new StringBuilder(); try { is=context.openFileInput(fileName); reader = new BufferedReader(new InputStreamReader(is)); String l=""; while((l=reader.readLine())!=null) { result.append(l); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(reader!=null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result.toString(); }

 

//写入文件   
public boolean write(Context context,String fileName,String content) { FileOutputStream os=null; BufferedWriter writer=null; try { os=context.openFileOutput(fileName,context.MODE_APPEND); writer=new BufferedWriter(new OutputStreamWriter(os)); writer.write(content); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(writer!=null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; }

 

2、下面使用的四个Environment的方法,获取当前运行环境的四个不同目录,返回一个File对象,我们可以依据这个File

对象进行新建、写入、读取等操作。对于不同厂商,对于sd卡手机内存的访问api可能会有修改,这些需要实际情况,实际分析。

        Log.i("info","getDataDirectory()"+Environment.getDataDirectory().getAbsolutePath());
        Log.i("info","getRootDirectory()"+Environment.getRootDirectory().getAbsolutePath());
        Log.i("info","getExternalStorageDirectory()"+Environment.getExternalStorageDirectory().getAbsolutePath());
        Log.i("info","getExternalStoragePublicDirectory()"+Environment.getExternalStoragePublicDirectory("basePath").getAbsolutePath());

 

posted @ 2017-07-22 08:59  授之以渔  阅读(795)  评论(0编辑  收藏  举报