当文件IS DIR时,文件isDirectory()给出false

时间:2012-12-11 16:54:18

标签: java android file

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

我的代码

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;
            }
        }
    });
}

1 个答案:

答案 0 :(得分: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;

检查是否需要额外的斜线,未经测试。