[英]Android: Problem to write/read file on external storage
I'm trying to write/read the external storage, after reading some questions here and on internet, exmeple etc. But i have problem in creating file in the SD, and it doesn't creates and loads, and the mkdirs
give me the error that it will be ignored: 我在这里和在互联网上,例如在阅读了一些问题之后,试图写/读外部存储。但是我在SD中创建文件时遇到了问题,它无法创建和加载,并且
mkdirs
给了我将被忽略的错误:
public EditText et;
public Button buttonSave,buttonLoad;
public TextView tv;
public String myData = "";
public File root = android.os.Environment.getExternalStorageDirectory();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
et = findViewById(R.id.inserimento);
buttonSave = findViewById(R.id.save);
buttonLoad = findViewById(R.id.load);
tv = findViewById(R.id.tv);
File dir = new File(root.getAbsolutePath() + "/eliminaCoda");
dir.mkdirs();
final File file = new File(dir, "Lista.txt");
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(et.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
et.setText("");
}
});
buttonLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
tv.setText(myData);
}
});
}
You have to add write uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" in AndroidManifest.xml file. 您必须在AndroidManifest.xml文件中添加写入uses-permission android:name =“ android.permission.WRITE_EXTERNAL_STORAGE” 。 Also, you have to request for runtime permission.
另外,您还必须请求运行时权限。
Please check this demo for runtime permission Runtime Permissions in Marshmallow 请检查此演示以获得运行时权限棉花糖中的运行时权限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.