Android sd卡的存与读

权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

检查权限

第一次使用应用时所需

 // 1、检查是否有读写sdcard的权限
    private void checkWriteAndReadPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                requestPermissions(permissions, 1000);
            }

        }
    }

建立文件夹

File fileDir= new File(Environment.getExternalStorageDirectory() + "/myfile");
fileDir.mkdirs();

写入txt文件

		File file=new File(fileDir,"ABC.txt");
        String content="这是写入的文件";
        OutputStream ou=null;

        try {
            file.createNewFile();
            ou=new FileOutputStream(file);
            ou.write(content.getBytes());
            ou.flush();
            Toast.makeText(this,"写入成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

读取txt文件

 		File file =new File(fileDir,"ABC.txt");
        if(file.exists()&&file.isFile()){
            InputStream in=null;
            try {
                StringBuilder stringBuilder = new StringBuilder();
                in=new FileInputStream(file);
                byte[] buffer=new  byte[4*1024];
                while (in.read(buffer)!=-1){
                    stringBuilder.append(new String(buffer));
                }
                textView.setText(stringBuilder.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
发布了16 篇原创文章 · 获赞 2 · 访问量 618

猜你喜欢

转载自blog.csdn.net/csdn_ggboy/article/details/105143247
今日推荐