[英]How to get all the filenames in android directory?
我試圖列出我的Android模擬器的特定文件夾中的所有文件,而我一直得到空答案。
這是我的代碼:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
這似乎不起作用,不知道為什么。
我將函數分為兩部分,第一個函數獲取給定路徑中的所有文件,第二個函數從文件數組中獲取文件名。
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
更改
File[] file= new File(sdCardRoot+"path");
與
File[] file= new File(sdCardRoot, "path");
並確保目錄path
退出
只需檢查一下:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
由於sdCardRoot
是File
實例,因此sdCardRoot+"path"
將返回與sdCardRoot.toString() + "path"
相同的東西。
但是,調用file.toString()
返回文件名,但不返回絕對路徑。 您需要調用sdCardRoot.getAbsolutePath() + "path"
。
另外,請確保已允許仿真器將一定數量的內存用於外部存儲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.