做文件管理器时isDirectory()判断错误原因及解决办法

isDirectory()

File[] files = pathfile.listFiles();

files中的file 用isDirectory()判断有问题,某些特殊文件夹出现isFile()判断为文件.


办法是通过父路径拼上文件名,
String fileName = file.getName();
File file = new File(patentPath + "/" + fileName);
重新生成File再判断。
(上述具体原因仍值得推敲,可能是代码的问题)


package com.example.filemgr;


import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity {
private String path;
private File[] files;
private ListView listView;
private TextView textView;
private Button btnBack;
private List data;
private String fileName;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


textView = (TextView) findViewById(R.id.textview_filepath);
listView = (ListView) findViewById(R.id.listview_files);
btnBack = (Button) findViewById(R.id.btn_back);
searchFiles();


MyAdapter myAdapter = new MyAdapter(this);


data = new ArrayList();
if (files != null) {
for (File file : files) {
data.add(file.getName());
}
Collections.sort(data);
}
myAdapter.setDataList(data);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {


@Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
fileName = data.get(position);
// String fileName = ((TextView)view).getText().toString();
// File file = files[position];//得到的File,isDirectory判断特殊文件夹错误!

//拼全路径重新生成File,正确判断
File file = new File(path + "/" + fileName);
if (file.isDirectory()) {
Intent intent = new Intent("com.hei.daizi.subactivity");
String fileAbsolutePath = path + "/" + fileName;
Toast.makeText(MainActivity.this, fileAbsolutePath,
Toast.LENGTH_SHORT).show();
intent.putExtra("path", fileAbsolutePath);
startActivity(intent);
} else if(file.isFile()){
Toast.makeText(MainActivity.this, fileName+"是一个文件",
Toast.LENGTH_SHORT).show();
}
}
});
btnBack.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
finish();
}
});


}


private void searchFiles() {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File rootFile = Environment.getExternalStorageDirectory();
String rootPath = rootFile.getAbsolutePath();


textView.setText(rootPath);


path = rootPath;


File pathfile = new File(rootPath);
files = pathfile.listFiles();
}
}


}

你可能感兴趣的:(android)