3

我想查看我的外部存储中的所有文件,我有这个库可以向用户显示文本,但是当我使用它来显示子文件时,它会说:
(Ljava.File;@
我如何得到它向用户显示实际文件的名称?另外,如何向用户显示特定文件夹的名称?说文件#3?

File[] files = myDir.listFiles();
UIHelper.displayText(this, R.id.textView1, files.toString());
4

3 回答 3

12

检查 sdcard 是否已安装。

 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
       ///mounted
}

获取sd卡的路径

 File dir= new File(android.os.Environment.getExternalStorageDirectory());

然后打电话

  walkdir(dir);

 ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with 

public void walkdir(File dir) {
 File listFile[] = dir.listFiles();

if (listFile != null) {
 for (int i = 0; i < listFile.length; i++) {

 if (listFile[i].isDirectory()) {// if its a directory need to get the files under that directory
  walkdir(listFile[i]);
} else {// add path of  files to your arraylist for later use

  //Do what ever u want
  filepath.add( listFile[i].getAbsolutePath());

 }
 }  
}    
}
于 2013-04-10T08:21:22.080 回答
4

这是从 ExternalStorage 打印文件和文件夹列表的代码

String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        Log.d("Files", "Path: " + path);
        File f = new File(path);        
        File file[] = f.listFiles();
        Log.d("Files", "Size: "+ file.length);
        for (int i=0; i < file.length; i++)
        {
            Log.d("Files", "FileName:" + file[i].getName());
        }

不要忘记在您的 android Manifest 中添加以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
于 2015-06-11T05:31:55.167 回答
1

You can use a recursive method to scan all your SD card:

String sdCardState = Environment.getExternalStorageState(); 
if( !sdCardState.equals(Environment.MEDIA_MOUNTED ) ) {
    //displayMessage("No SD Card.");
    return;
} else {
    File root = Environment.getExternalStorageDirectory();
    lookForFilesAndDirectories(root);
}

// lookForFilesAndDirectories() method:

public void lookForFilesAndDirectories(File file) {
    if( file.isDirectory() ) {
        String[] filesAndDirectories = dir.list();
        for( String fileOrDirectory : filesAndDirectories) {
            File f = new File(dir.getAbsolutePath() + "/" + fileOrDirectory);
            lookForFilesAndDirectories(f);
        } 
    } else {
        doSomethingWithFile(f);
    }
}
于 2013-04-10T07:53:11.307 回答