簡體   English   中英

java.nio.file.AccessDeniedException 在創建應用程序時使用android studio,但在eclipse中只有java沒有問題

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM