外部私有目录的操作
Android6.0后采用沙盒模式,不许在根目录下随意创建文件
所需权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
也可以使用旧的策略。在Android.xml中添加
android:requestLegacyExternalStorage="true"
这里只介绍私有目录和内部存储
//初始化私有路径: /Android/data/包名/files
String path = getExternalFilesDir("").getAbsolutePath();
文件夹的创建
File jia = new File(path + “/mingz”);
jia.mkdirs();
File jia = new File(path + "/mingz");
if (jia.exists()) {
Toast.makeText(this, "文件夹已经存在", Toast.LENGTH_SHORT).show();
} else {
jia.mkdirs();
}
普通文件创建
File wj = new File(path + “/ces.txt”);
wj.createNewFile();
File wj = new File(path + "/ces.txt");
if (wj.exists()) {
Toast.makeText(this, "文件存在", Toast.LENGTH_SHORT).show();
} else {
try {
wj.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
读取与写入操作
内部存储:使用openFileOutput建立输出流
内部存储必须root才能查看
外部储存:使用FileOutputStream建立输出流
内部存储:
File xie = new File(path + "/ces.txt");
try {
//用MODE_PRIVATE,意为私有模式(会覆盖原文件)
FileOutputStream fileOutputStream =openFileOutput("ces.txt", MODE_PRIVATE);
byte[] bytes = "写入文件文本ces".getBytes();
fileOutputStream.write(bytes);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
内部存储:读取文件
try {
FileInputStream fileInputStream = openFileInput("ces.txt");
byte[] buffer = new byte[fileInputStream.available()];
fileInputStream.read(buffer);
String dq = new String(buffer);
textView.setText(dq);
} catch (Exception e) {
e.printStackTrace();
}
外部储存:
try {
FileOutputStream fileOutputStream = new FileOutputStream(path + "/ces.txt");
byte[] bytes = "外部文件的写入文件文本ces22222".getBytes();
fileOutputStream.write(bytes);
Toast.makeText(this, "外部文件写入成功", Toast.LENGTH_SHORT).show();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
外部读取
try {
// 唯一不同
FileInputStream fileInputStream = new FileInputStream(path + "/ces.txt");
byte[] buffer = new byte[fileInputStream.available()];
fileInputStream.read(buffer);
String dq = new String(buffer);
textView.setText(dq);
} catch (Exception e) {
e.printStackTrace();
}
输出图片并更新系统相册
path = getExternalFilesDir("").getAbsolutePath();//地址
String picname="ces123.jpg";//名字
String zzpath=path+"/"+picname;//将地址转换为文本真正的地址值
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.shuchu);//Bitmap图片
File file=new File(path,picname);//文件
try {
FileOutputStream fileOutputStream=null;
fileOutputStream=new FileOutputStream(file);//输出
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fileOutputStream);// bitmap转换成输出流,写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//-----------------更新系统相册
try {
MediaStore.Images.Media.insertImage(getContentResolver(), zzpath, "titleww", "description");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(zzpath)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}