Android数据存储与IO之三(File存储之ExternalStorage)

Android数据存储与IO三(File存储ExternalStorage

 

    当程序利用Context提供的openFileinput或者openFileOutput打开文件输入、输出流时,程序打开的都是/data/data/<package>/files/下的文件,这样存储的空间可能有限并且保存在/data/data/<package>目录中文件,会在卸载应用程序时被删除掉,这可能会带来一些问题,为了更好的存取应用程序的大文件数据,应用程序需要读、写SD卡上的文件。读写SD卡的文件步骤如下所示:

1.调用Environment的getExternalStorageState().方法判断手机是否插入了SD卡并且具有读写SD卡的权限具体如下

      当Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTEDtrue时说明已经插入SD卡并且具有读写权限,注意,这里的读写权限需要在编写程序中添加,具体方法是在AndroidManifest.xml文件中添加

           <uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>//具有创建与删除的权限

          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>//具有修改的权限

          <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />//具有读取的权限

   来获得权限

2.调用EnvironmentgetExternalStorageDirectory()方法来获取SD开的目录

3.使用FileInputStreamFileOutputStreamFileReaderFileWriter读写SD卡中的文件,其方法与读写本机内存中的文件方法类似

   最后同样的,一定要记得关闭IO

  下面我们利用SD卡进行简单的文件读写

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

test08 = (TextView) findViewById(R.id.TEST);

fileName = "/test08.txt";

write("hhhhhhhhhhhhhhhhhhhhhhhhhhhhh");

read();

}

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

    public void write(String str){

     if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断当前状态

     File sdCardDir=Environment.getDataDirectory();//获得SD卡路径

     try {

File file=new File(sdCardDir.getCanonicalPath()+fileName);//获得文件路径

RandomAccessFile raf=new RandomAccessFile(file,"rw");//RandomAccessFile是向指定文件中添加内容,FileOutputStream是直接覆盖原有文件内容

raf.seek(file.length());//将文件记录指针移到文件最后

raf.write(str.getBytes());//输出文件内容

raf.close();//关闭IO流

catch (Exception e) {

e.printStackTrace();

}

     }

    }

    public void read(){

     if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

     File sdCardDir=Environment.getDataDirectory();

     BufferedReader  buf;

     try {

File file=new File(sdCardDir.getCanonicalPath()+fileName);

FileInputStream fis=new FileInputStream(file);

buf=new BufferedReader(new InputStreamReader(fis));

StringBuffer strbuf=new StringBuffer();

String line=null;

while((line=buf.readLine())!=null){//循环读取所有字符

strbuf.append(line);

}

buf.close();

test08.setText(strbuf.toString());

catch (Exception e) {

}

    

     }else{

     }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值