简体   繁体   English

如何在android设备中查找所有文件并将它们放在列表中?

[英]How to look up for all files in an android device and put them in a list?

I looking for help to list all files in android external storage device. 我正在寻找帮助以列出Android外部存储设备中的所有文件。 I want to look up in all the folders including the subfolders for the main folder. 我想查找所有文件夹,包括主文件夹的子文件夹。 Is there any way to this? 有什么办法吗?

I have worked on a basic one but still haven't get the desired result. 我已经完成了一项基本的工作,但仍然没有得到理想的结果。 It doesn't work. 没用 Here is my code: 这是我的代码:

File[] files_array;
files_array = new File(Environment.getExternalStorageDirectory().getAbsolutePath()).listFiles();

Please help. 请帮忙。 Thank you. 谢谢。

Edit: 编辑:

This method returns 0 size. 此方法返回0大小。 I don't know what is the matter. 我不知道怎么回事。 This is my activity: 这是我的活动:

public class Main extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<File> files = getListFiles(Environment.getExternalStorageDirectory());
        setListAdapter(new ArrayAdapter<File>(Main.this, android.R.layout.simple_list_item_1, files));
        Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
    }

    private List<File> getListFiles(File parentDir) {
        // On first call, parentDir is your sdcard root path
        ArrayList<File> inFiles = new ArrayList<File>(); // initialize an array list to store file names
        File[] files = parentDir.listFiles(); // list all files in this directory
        for (File file : files) {
            if (file.isDirectory()) { // if the file is a directory
                inFiles.addAll(getListFiles(file)); // **CALL THIS RECURSIVELY TO GET ALL LOWER LEVEL FILES**
            } 

        }
        return inFiles;
    }
}
public void Search_Dir(File dir) {
    String pdfPattern = ".pdf";

    Log.d("check",
            "Environment.getExternalStorageDirectory()------"
                    + dir.getName());

    File FileList[] = dir.listFiles();
    Log.d("check",
            "filelist length---- "
                    + FileList.length);

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

            if (FileList[i].isDirectory()) {
                Search_Dir(FileList[i]);
            } else {

                Log.d("check",
                        "for check from .pdf---- "
                                + FileList[i].getName());
                if (FileList[i].getName().endsWith(pdfPattern)) {
                    // here you have that file.
                    pdfArrayList.add(FileList[i].getPath());

                }
            }
        }
    }

}

Conceptually, what you are doing is not complete. 从概念上讲,您正在做的事情并不完整。 Your code only gives you a File for the root level directory. 您的代码仅为您提供根目录的文件。 To determine all the files within this directory and the sub directories, you need recursive calls so that all the files are listed to the end of the folder levels. 要确定此目录和子目录中的所有文件,您需要递归调用,以便将所有文件列出到文件夹级别的末尾。

private List<File> getListFiles(File parentDir) {
    // On first call, parentDir is your sdcard root path
    ArrayList<File> inFiles = new ArrayList<File>(); // initialize an array list to store file names
    File[] files = parentDir.listFiles(); // list all files in this directory
    for (File file : files) {
        if (file.isDirectory()) { // if the file is a directory
            inFiles.addAll(getListFiles(file)); // **CALL THIS RECURSIVELY TO GET ALL LOWER LEVEL FILES**
        } 

    }
    return inFiles;
}

Now call this function as: 现在将该函数称为:

getListFiles(Environment.getExternalStorageDirectory());

Now, you can add your ArrayList as a source to a List Control. 现在,您可以将ArrayList作为源添加到List控件。

Bonus : If you would like to represent list the files in a tree like view, I would recommend you to look at https://code.google.com/p/tree-view-list-android/ 奖励 :如果您希望以树状视图的形式列出文件,建议您查看https://code.google.com/p/tree-view-list-android/

Source: List all the files from all the folder in a single list 源: 在一个列表中列出所有文件夹中的所有文件

Search all .pdf file present in the Android device 搜索Android设备中存在的所有.pdf文件

I have found a solution somewhere on the web and I asked my self why not share it. 我在网络上的某个地方找到了一个解决方案,我问自己为什么不共享它。

        public void walkdir(File dir) {

        File[] listFile;
        listFile = dir.listFiles();

        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkdir(listFile[i]);
                } else {
                  if (listFile[i].getName().toLowerCase().endsWith(".pdf")){
                      files_list.add(listFile[i]);
                  }
                }
            }
        }    
    }

All what you need actually is calling the method above with the parent dir that you want to start with. 您实际上所需的全部就是使用您要开始的父目录调用上述方法。 I recommend to put Environment.getExternalStorageDirectory() in the parent directory so it will not change with different devices. 我建议将Environment.getExternalStorageDirectory()放在父目录中,这样它就不会随其他设备而改变。

Can you please try with this: The java.io package has been reimplemented within Android. 您能尝试一下吗: java.io软件包已在Android中重新实现。 You are able to use the same mechanisms in Android as you do in Java. 您可以在Android中使用与Java中相同的机制。

File fileList = new File("/sdcard"); // path which you want to read
if (fileList != null){
    File[] files = fileList.listFiles();
        for (File f : files){
            //Do something with the files
        }
    }
}

I used this code, hope it helps: 我使用了这段代码,希望对您有所帮助:

    private File[] listOfDir;

    ...

    TextView tv = (TextView) rootView.findViewById(R.id.textView1);
    listOfDir = show();
    String temp = "";
    if (listOfDir != null) {
        for (File i : listOfDir) {
            temp += i.getName() + '\n';
        }
    } else {
        temp = "null";
    }
    tv.setText(temp);
    ...

  public File[] show() {
    File[] dirs = null;
    File dir = new File(*your path*);
    dirs = dir.listFiles();
    return dirs;
}

and just call show to get list all the name 然后打电话给show列出所有名字

I think this will help. 我认为这会有所帮助。 First you need to fetch the contents of the sd card as shown below: 首先,您需要获取sd卡的内容,如下所示:

public class FileList extends ListActivity 
{
private File file;
private List<String> myList;

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    myList = new ArrayList<String>();   

    String root_sd = Environment.getExternalStorageDirectory().toString();
    file = new File( root_sd + "/external_sd" ) ;       
    File list[] = file.listFiles();

    for( int i=0; i< list.length; i++)
    {
            myList.add( list[i].getName() );
    }

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, myList ));

}

Now that you have all the files and folders from your sdcard in your listview , whenever, you go into a folder, then you need to fetch the contents of that folder as shown below: 现在,您已经在listview拥有了sdcard中的所有文件和文件夹,无论何时进入一个文件夹,那么您都需要获取该文件夹的内容,如下所示:

protected void onListItemClick(ListView l, View v, int position, long id) 
{
    super.onListItemClick(l, v, position, id);

    File temp_file = new File( file, myList.get( position ) );  

    if( !temp_file.isFile())        
    {
        file = new File( file, myList.get( position ));
        File list[] = file.listFiles();

        myList.clear();

        for( int i=0; i< list.length; i++)
        {
            myList.add( list[i].getName() );
        }
        Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show(); 
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, myList ));

    }

}

And again on pressing back you need to load back the contents of your previous folder as shown below: 再按一次,您需要重新加载上一个文件夹的内容,如下所示:

@Override
public void onBackPressed() {
            String parent = file.getParent().toString();
            file = new File( parent ) ;         
            File list[] = file.listFiles();

            myList.clear();

            for( int i=0; i< list.length; i++)
            {
                myList.add( list[i].getName() );
            }
            Toast.makeText(getApplicationContext(), parent,          Toast.LENGTH_LONG).show(); 
            setListAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, myList ));


    }

I think this is what you need. 我认为这就是您所需要的。

Wrote a tutorial on this a while ago. 前不久写了一篇关于这个的教程。 Still use this from time to time. 仍会不时使用此功能。 Have a look, you might find what you need. 看看,您可能会找到所需的东西。 playing-with-sdcard-in-android 在Android中玩SD卡

Try this: If you don't want directory to be listed put files.add(file1[i]); 尝试以下操作:如果您不希望列出目录,则将files.add(file1 [i]); line in else block 行在else块中

public class MainActivity extends ListActivity {
ArrayList<File> files = new ArrayList<File>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    File file[] = Environment.getExternalStorageDirectory().listFiles();
    recursiveFileFind(file);

    setListAdapter(new ArrayAdapter<File>(MainActivity.this,
            android.R.layout.simple_list_item_1, files));
    Toast.makeText(this, "" + files.size(), Toast.LENGTH_LONG).show();
}

public void recursiveFileFind(File[] file1) {
    int i = 0;
    String filePath = "";
    if (file1 != null) {
        while (i != file1.length) {
            filePath = file1[i].getAbsolutePath();
            files.add(file1[i]);
            if (file1[i].isDirectory()) {
                File file[] = file1[i].listFiles();
                recursiveFileFind(file);
            }else{
                            }

            i++;
            Log.d(i + "", filePath);
        }
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM