向sd卡读写数据

/data/data 是本地存储

/storage/ 是外部存储

SD卡存储

 



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


public void writeToSdCard() throws IOException { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE); } else { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String name = et_of_name.getText().toString(); String content = et_of_content.getText().toString(); String dir = getExternalFilesDir(null).getAbsolutePath(); dir = dir + "/" + name; FileOutputStream fos = new FileOutputStream(dir); fos.write(content.getBytes("utf-8")); fos.close(); Toast.makeText(this, "save to external sdcard", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "without external sdcard", Toast.LENGTH_SHORT).show(); } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_CODE: if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { try { writeToSdCard(); } catch (IOException e) { Toast.makeText(this, "failed save to external sdcard", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "Write External SDCARD Permission Not Granted", Toast.LENGTH_SHORT).show(); } break; default: break; } }

 

    public void read(View v) throws IOException {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String name = et_of_name.getText().toString();
            String dir = getExternalFilesDir(null).getAbsolutePath();
            dir = dir + "/" + name + "txt";
            InputStream fis = new FileInputStream(dir);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len = -1;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                bos.write(bytes);
            }
            String content = bos.toString();
            et_of_content.setText(content);
        } else {
            Toast.makeText(this, "without external sdcard", Toast.LENGTH_SHORT).show();
        }
    }

判断文件夹是否存在
File file = new File(dir);
if(!file.exists()) {
file.mkdir();
}
 
String dir =
 context.getExternalFilesDir(null).getAbsolutePath();

 /storage/emulated/0/Android/data/com.example.storage/files

Environment.getExternalStorageDirectory().getAbsolutePath()

/storage/emulated/0

转载于:https://www.cnblogs.com/znsongshu/p/9335172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值