Upon request, here is the log file when I press the button我已经浏览了互联网,这个论坛和youtube,试图弄清楚如何将简单的txt文件写入外部存储。我在youtube上找到了这个很棒的教程:
https://www.youtube.com/watch?v=kerqarY7_wQ
我按照他的代码来发球。但是,当我调用下面显示的方法时,没有任何反应。没有异常被抛出,文件没有被创建,我也看不到任何我的故障安全消息通过Toast弹出屏幕。怎么了?!?!我确保将权限添加到清单文件,并且按钮肯定会调用正确的方法。作为参考,我尝试了他的内部存储写作教程,它完美无缺。我不明白它是如何不显示任何消息的,因为即使它无法写入存储,也应该告诉我。代码如下,我真的很感激任何帮助。
//Permissions files in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
//Method in main java file
public void writeExternalStorage(View view) {
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File Dir = new File(root.getAbsolutePath()+"/MyAppFile");
if(!Dir.exists()) {
Dir.mkdir();
}
File file = new File(Dir,"Test.txt");
String message = editText.getText().toString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(message.getBytes());
fileOutputStream.close();
//the editText variable is the text field on the app.
editText.setText("");
Toast.makeText(getApplicationContext(), "Message Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "SD Card not found.",Toast.LENGTH_LONG).show();
}
}