/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