在我的 fragment 中,我有文件和文件夹列表,还有一个用于文件位置的 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;
}
}
});
}
最佳答案
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,它未经测试。
关于java - 当文件是目录时,文件 isDirectory() 给出 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824804/