外部存储,个人理解是在app作用域之外存储,就是数据没有和app做关联,app卸载后,它依旧存在
而不再是之前手机本身存储空间和sd卡的区别,现在安卓手机已经不携带可拆卸的SD卡
androidManifest.xml 需要写入读写权限
简单布局:
java代码: 需要动态权限,android8以后,真机都需要,模拟器可能不需要
package com.example.handleproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class externalActivity extends AppCompatActivity {
private TextView mTextView;
private Button save;
private Button read;
private TextView showText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_external);
mTextView=findViewById(R.id.text);
save=findViewById(R.id.save);
read=findViewById(R.id.read);
showText=findViewById(R.id.showTxt);
int permisson= ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(permisson!= PackageManager.PERMISSION_GRANTED){
// TODO: 2020-08-14 动态申请权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
}
}
public void oprerate(View v){
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/imooc.txt";
Log.d("External", path);
switch (v.getId()){
case R.id.save:
File f=new File(path);
try{
if(!f.exists()){
f.createNewFile();
}
//用追加的模式写入
FileOutputStream fos=new FileOutputStream(path,true);
String str=mTextView.getText().toString();
fos.write(str.getBytes());
}catch (IOException E){
Log.d("External err", E.getMessage());
}
break;
case R.id.read:
try{
FileInputStream fis=new FileInputStream(path);
byte[] b=new byte[1024];
int len=fis.read(b);
String str2=new String(b,0,len);
showText.setText(str2);
fos.close();//不要忘记关闭写入
}catch (IOException E){
E.printStackTrace();
}
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
存储地址在mnt/sdcard(androidStudio上面查看) 的更目录下面,在手机上看时候其实是在根目录下(手机文件管理器显示是"内部存储",也可能是其他的)
更详细的说明