写入和读取外部存储文件

时间:2022-09-06 11:55:24
 //写入外部存储文件
    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();
            }
        }
    }