1、检查是否有读写sdcard的权限
(1)首先要在AndroidManifest.xml加入
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果AndroidManifest.xml没有加入上面两条权限,是不可能进行动态权限申请的。动态权限申请,需要先在AndroidManifest.xml配置相应的权限。
(2)动态申请SD卡读写权限
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);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int permission : grantResults) {
if (permission == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "申请权限失败", Toast.LENGTH_LONG).show();
break;
}
}
}
2、创建文件目录
private boolean createDir(String dir) {
File fileDir = new File(dir);
if (fileDir.exists() && fileDir.isDirectory()) {
return true;
} else {
return fileDir.mkdirs();
}
}
3、创建文件
private File createFile(String fileName) {
File file = new File(fileDir, fileName);
if (file.exists() && file.isFile()) {
return file;
} else {
try {
if (file.createNewFile()) {
return file;
} else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
4、向文件写入数据
private void write2File(File file, String data) {
OutputStream ou = null;
try {
ou = new FileOutputStream(file);
byte[] buffer = data.getBytes();
ou.write(buffer);
ou.flush();
Toast.makeText(this,"写入成功",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ou != null) {
ou.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
整个过程大概如此,Demo在Github上,欢迎下载学习。
谢谢阅读!