1

在我的片段中,我有文件和文件夹的列表,还有一个用于文件位置的 onclick 侦听器。我试图只打开目录而不是文件,但即使文件是目录,我的方法 isDirectory() 总是给我 false。

我的代码

void fileList(String s) {
    currentPath = s;
    items = new ArrayList<String>();
    path = new ArrayList<String>();
    File f = new File(s);
    File[] files = f.listFiles();

    for(int i = 0; i < files.length; i++) {
        File file = files[i];

            if(!file.isHidden() && file.canRead()) {
            path.add(file.getPath());

            if(file.isDirectory()) {
                items.add(file.getName() + "/");
            }

            else {
                items.add(file.getName());
            }
        }
    }
    MyAdapter adapter = new MyAdapter(getActivity(), R.layout.row, items);
    ListView myList = (ListView) view.findViewById(R.id.list);
    myList.setAdapter(adapter);
    myList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            File f = new File(items.get(arg2));
            if(f.isDirectory()) { // <-its always give me false here;
                fileList(path.get(arg2));
            }
            else {
                return;
            }
        }
    });
}
4

1 回答 1

4
File f = new File(items.get(arg2));
if(f.isDirectory()) { // <-always false because it is a new File...

使用完整路径创建文件,而不仅仅是名称,或者它正在使用目录名称在您的位置创建一个新的空文件,而不是指向目录...

File f = new File(path.get(arg2) + "/" + items.get(arg2));
if(f.isDirectory()) { // <-now it will perform the check;

检查您是否需要额外的 Slash,它未经测试。

于 2012-12-11T17:00:50.083 回答