向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; } }

猜你喜欢

转载自www.cnblogs.com/znsongshu/p/9335172.html