获取存储路径以及读写

来源:互联网 发布:行知学园高田马场地址 编辑:程序博客网 时间:2024/06/10 17:36

首先给大家介绍两个方法,getFilesDir()和getCacheDir()

getCacheDir()方法用于获取/data/data/cache目录
getFilesDir()方法用于获取/data/data/files目录

然后我们看看怎么读写getFilesDir方法对应路径下的文件,系统提供了两个方法openFileOutput()和openFileInput()。

  /**将数据写入系统默认位置     * @param text     * 要保存的字符     */    public void write(String text)    {        try {        //通过openFileOutput方法得到一个输出流,方法参数为创建的文件名(不能有斜杠),操作模式            FileOutputStream fos=this.openFileOutput("myfirst.txt", Context.MODE_WORLD_READABLE);            fos.write(text.getBytes());//写入            fos.close(); // 关闭输出流        //弹出Toast消息            Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();        } catch (FileNotFoundException e) {            e.printStackTrace();        }        catch (IOException e){            e.printStackTrace();        }    }
/**读取文件*/public void read(){try {FileInputStream fis=this.openFileInput("myfirst.txt"); //获得输入流//用来获得内存缓冲区的数据,转换成字节数组ByteArrayOutputStream stream=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int length=-1;while((length=fis.read(buffer))!=-1) {stream.write(buffer,0,length);//获取内存缓冲区中的数据}stream.close(); //关闭fis.close();tv.setText(stream.toString()); //设置文本控件显示内容Toast.makeText(MyFile.this,"读取成功",Toast.LENGTH_LONG).show();//弹出Toast消息} catch (FileNotFoundException e) {Toast.makeText(MyFile.this, "文件不存在", Toast.LENGTH_SHORT).show();e.printStackTrace();}catch (IOException e){e.printStackTrace();}
0 0
原创粉丝点击