問題:我試圖使用隱式Intent(ACTION_GET_CONTENT)
打開txt文件,並將txt文件的內容存儲到數組列表中。當我嘗試使用Uri的getPath()
的文件路徑打開文件並創建一個BufferedReader
對象來從文本文件中讀取時,出現錯誤提示此類文件路徑不存在。Android:使用隱式意圖讀取txt文件
在logcat的,它說我的文件路徑"/document/1505-2A0C:Download/text.txt"
,當我嘗試打開該文件時,它說:
"W/System.err: java.io.FileNotFoundException:
/document/1505-2A0C:Download/text.txt: open failed:
ENOENT (No such file or directory)"
這裏是我的代碼:
@Override
public void onClick(View v) {
// Send implicit intent to load a file from directory
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
startActivityForResult(Intent.createChooser(intent,
"Load a file from directory"), REQUEST_CODE_SEARCH);
}
onActivityResult()
:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_SEARCH) {
try {
Uri uri = data.getData();
String filepath = uri.getPath();
// In logcat : File path: /document/1505-2A0C:Download/text.txt
Log.d("File path", filepath);
File file = new File(filepath);
ArrayList<String> strings = new ArrayList<>();
/* Problem occurs here : I do not get correct file path to open a FileReader.
In logcat: "W/System.err: java.io.FileNotFoundException:
/document/1505-2A0C:Download/text.txt: open failed:
ENOENT (No such file or directory)"*/
BufferedReader br = new BufferedReader(new FileReader(file));
// Rest of code that converts txt file's content into arraylist
} catch (IOException e) {
// Codes that handles IOException
}
}
}
總結:我得到"/document/1505-2A0C:Download/text.txt"
爲文件路徑,當我使用文件路徑在BufferedReader
中打開文件時,它說沒有這樣的目錄。
我在這裏做錯了什麼?