获取存储路径以及读写

首先给大家介绍两个方法,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值