在AndroidMainfest声明读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在mainActiviry.java的onCreate动态弹窗请求一个权限
public void requestPermissionAll(){
// 安卓版本检查,因为下面的checkSelfPermission以及shouldShowRequestPermissionRationale都是API23才开始支持的
// API23是android6.0,即android M
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//权限检查
if (checkSelfPermission(WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE}, 100);
} else {
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
}
这是一个java的代码,在Download目录里面写一个文件作为示范
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + "/test.log");
//写一个文本
try {
out = new FileOutputStream(file);
out.write("我是字符串".getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
写了肯定是要读出来吧
String readme="";
try {
in = new FileInputStream(file);
//使用缓冲来读
byte[] buf = new byte[1024];//每1024字节读一次
StringBuilder builder = new StringBuilder();
while (in.read(buf) != -1) {
builder.append(new String(buf).trim());
}
readme = builder.toString();
} catch (Exception e) {
e.printStackTrace();
}