因此,我使用手機上的Excel創建了名爲theBook.csv
的文件,該文件已保存到手機的Documents
文件夾中。當我嘗試列出手機的Documents
文件夾的內容時,我收到一個NullPointerException
,說我試圖to get length of null array
。無法在Android文檔目錄中列出或打開文件
這是我曾嘗試:
String path = Environment.getExternalStorageDirectory().toString() + "/Documents";
// I have also tried:
// String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
// and
// String path = Environment.getRootDirectory().getAbsolutePath() + "/Documents";
Log.i("Files", "The path is: " + path);
File f = new File(path);
File file[] = f.listFiles();
try {
Log.i("Files", "Number of files: "+ file.length);
for (int i = 0; i < file.length; i++) {
Log.i("Files", "Found file with name:" + file[i].getName());
}
} catch (NullPointerException e) {
entoast("NPE"); // my toast message method
e.printStackTrace();
}
當我查看日誌的path
值/storage/emulated/0/Documents
(無論是哪個三條線我嘗試的),而我不能確定對應到Documents
文件夾,其中theBook.csv
位於。如果是這樣,爲什麼不在日誌文件中顯示theBook.csv
?如果沒有,我怎麼讓我的程序訪問手機的實際Documents
文件夾,而不是一個空目錄?
當手機通過USB連接進行文件傳輸時,Documents文件夾可以查看,而且在使用手機內置的文件瀏覽器時也是可觀的。我在手機上運行Android 6.0,但該應用的最低要求SDK是Android 4.1。我的清單文件中也有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
行。
您必須添加'的完整列表<使用許可權的android:NAME =「android.permission.READ_EXTERNAL_STORAGE 「/>'在清單文件中。 –
READ_EXTERNAL_STORAGE屬於危險類別權限,您應該請求權限運行時間。此功能已添加到Android 6.0中 – USKMobility