[英]How to read files from external storage "Documents" in Android 10?
Android 开发新手,我需要帮助。
此代码/功能在 Android Studio 的内置仿真器中使用 Android 11。
private String[] getData(String filename) throws IOException {
FileInputStream fin = null;
int ch;
StringBuffer sb = new StringBuffer();
String text = "";
String[] fragments = new String[0];
try{
fin = new FileInputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+filename);
while((ch = fin.read()) != -1) {
sb.append((char)ch);
}
text = sb.toString();
fragments = text.split(";");
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
// close the stream using close method
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
return fragments;
}
代码只是读取公用文件夹“Documents”中的文件并将内容作为字符串数组返回。 但由于某种原因,此代码在 Android 10 中不起作用。
清单文件包括这两个请求:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
您可以使用相同的代码。
但是对于 Android 10 设备,您应该添加
requestLegacyStorageLocation="true"
(或类似的东西)在清单文件的应用程序标签中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.