![](/img/trans.png)
[英]java.nio.file.AccessDeniedException when reading a file
[英]java.nio.file.AccessDeniedException with android studio when creating an app but no issues with only java in eclipse
此代码在 java 读取我的笔记本电脑中的文件时没有问题,但是当我尝试使用 Android studio v 9.0 创建应用程序时,到目前为止,该应用程序无法读取位于我手机中的此文件。
String thePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
路径文件位置 = Paths.get(thePath + "/v.txt");
所以 fileLocation 被作为参数传递给这个方法:
public void mainOperation(Path fileLocation) throws IOException {
if (!Files.exists(fileLocation)) {
System.out.println("File Doesn’t exist. Exiting…");
System.exit(1);
}
StringBuilder mysb = new StringBuilder();
// problem is when trying to read the file, in the below line
for (String str : Files.readAllLines(fileLocation, Charset.defaultCharset())) {
System.out.println("reading....");
mysb.append(str);
mysb.append(";");
if (str.contains(END_VCARD)) {
System.out.println(startProcess(mysb.toString()));
mysb = new StringBuilder();
}
}
}
当我调试应用程序时,我看到错误来自 MainActivity.java 中的此处:
binding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProcessVcard myprocessVcard = new ProcessVcard();
String thePath =
String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
Path fileLocation = Paths.get( thePath + "/v.txt");
try {
myprocessVcard.mainOperation(fileLocation);
} catch (IOException e) {
e.getCause(); //
e.printStackTrace();
}
并且 IOException 被以下错误捕获:java.nio.file.AccessDeniedException: /storage/emulated/0/Download/v.txt
我确实在 AndroidManifest.xml 文件中添加了使用权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app4">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
我也尝试了清洁项目的选项,但到目前为止还没有任何乐趣。
v.txt 可以在我的手机中打开。 另外,请参阅 Android Studio 中的 Device File Explore 视图:
有什么建议吗?
非常感谢
在 Android 11+ 上,使用文件系统 API 或MediaStore
时,您无法访问其他应用程序放在Downloads/
中的文件。
相反,您可以使用ACTION_OPEN_DOCUMENT
/ ActivityResultContracts.OpenDocument
。 这将允许用户将文件放置在用户想要的任何位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.