gpt4 book ai didi

java - Android:在外部存储上写入/读取文件时出现问题

转载 作者:行者123 更新时间:2023-12-02 10:51:17 27 4
gpt4 key购买 nike

在阅读了此处和互联网上的一些问题(例如等)后,我正在尝试写入/读取外部存储。但我在 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);
}
});
}

最佳答案

您必须在 AndroidManifest.xml 文件中添加 write uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 。此外,您必须请求运行时权限。

请检查此演示的运行时权限 Runtime Permissions in Marshmallow

关于java - Android:在外部存储上写入/读取文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52165587/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com