写入和读取外部存储文件

 //写入外部存储文件
    public  void bt6_OnClick(View v)
    {
        //1.判断sd卡是否挂载
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            //文本框内容
            String str=et_1.getText().toString();
            try {
                //写入
                //1.构造输出流
                //1)得到文件路径
                //得到sd卡的根目录
//                String path=Environment.getExternalStorageDirectory()
//                        .getCanonicalPath();
                //得到包名对应的目录
                String path=getExternalFilesDir("Music").getCanonicalPath();
                Toast.makeText(MainActivity.this, "path="+path, Toast.LENGTH_LONG).show();
                //2)构造
                FileOutputStream fos = new FileOutputStream(path+"/test.txt");
                PrintStream ps=new PrintStream(fos);
                ps.print(str);
                fos.close();
                ps.close();
                Toast.makeText(MainActivity.this, "写入文件成功", Toast.LENGTH_SHORT).show();
            }catch (Exception e)
            {
                Toast.makeText(MainActivity.this, "存储文件出错", Toast.LENGTH_SHORT).show();
            }
        }else
        {
            Toast.makeText(MainActivity.this, "sd卡没有挂载", Toast.LENGTH_SHORT).show();
        }
    }
    //读取外部存储文件
    public  void bt7_OnClick(View v)
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            try
            {
                String path=getExternalFilesDir("Music").getCanonicalPath()+"/test.txt";
                FileInputStream fis=new FileInputStream(path);
                byte[] b=new byte[1024];
                int i=0;
                String str="";
                while ((i=fis.read(b))>0)
                {

                    str+=new String(b,0,i);
                }
                fis.close();
                Toast.makeText(MainActivity.this, "文件内容="+str, Toast.LENGTH_SHORT).show();

            }catch (Exception e)
            {
                Toast.makeText(MainActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

 

转载于:https://www.cnblogs.com/jiang2538406936/p/5536804.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值