我需要用戶從存盤中選擇一個檔案。一旦用戶選擇了檔案,我就無法對它做任何事情,因為它回傳一個例外“檔案不存在”,盡管它肯定存在。授予了權限,我什至獲得了持久的 URI 權限。這個示例代碼不是最漂亮的,我知道,但它仍然不應該給我我認為的那個 excpetion。我寫錯了什么或者可能導致這個問題?
目前,此示例代碼不會引發例外,但如果陳述句失敗并記錄“檔案不存在”。我需要它通過 if 陳述句并呼叫 openMap()。如果我要洗掉 if 陳述句,我會得到org.mapsforge.map.reader.header.MapFileException: file does not exist: content:/com.android.externalstorage.documents/document/primary:estonia.map
final ActivityResultLauncher<Intent> sARL = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK){
Intent data = result.getData();
assert data != null;
Uri uri = data.getData();
File oFile = new File(uri.getPath());
getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (new File(uri.getPath()).exists()){
openMap(oFile);
}else{
Log.w("File", "File does not exist");
}
}
}
});
public void openFileDialog(){
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
data = Intent.createChooser(data, "Choose tile");
sARL.launch(data);
}
uj5u.com熱心網友回復:
試試下面的代碼
File oFile = new File(data.getData().getPath());
if (oFile.exists()){
Toast.makeText(this, "exist: " oFile.exists(), Toast.LENGTH_SHORT).show(); //returns true
openMap(oFile);
}else{
Log.w("File", "File does not exist");
}
如果問題還沒有解決,請告訴我。
uj5u.com熱心網友回復:
問題出在 Uri 上。如果我對檔案的路徑進行硬編碼,那么一切都很好,但是據我所知,通過檔案選擇意圖,我實際上無法訪問真實的檔案路徑。檔案內容仍然可以讀取,但我需要路徑。
File oFile = new File(Environment.getExternalStorageDirectory() filePath)
這成功了,我加載了實際的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/522400.html
標籤:爪哇安卓工作室文件乌里
上一篇:任務':app:generateDebugApolloIR'(type'ApolloIRGenTask')的配置發現了一些問題
