在这里和互联网,示例等问题上阅读后,我试图写/读外部存储。
但是我在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);
}
});
}
答案 0 :(得分:1)
您必须在AndroidManifest.xml文件中添加写入 uses-permission android:name =“ android.permission.WRITE_EXTERNAL_STORAGE” 。另外,您还必须请求运行时权限。
请检查此演示以获得运行时权限 Runtime Permissions in Marshmallow