//items 存放显示的名称 paths存放文件路径 rootPath起始目录
private List<String> items = null;
private List<String> paths = null;
private String rootPath = "/";
private TextView mPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPath = (TextView) findViewById(R.id.textView1);
getFileDir(rootPath);
}
private void getFileDir(String filePath) {
mPath.setText(filePath);
items = new ArrayList<String>();
paths = new ArrayList<String>();
File files = new File(filePath);
File [] f = files.listFiles();
if(!filePath.equals(rootPath)){
//第一个设置为回到根目录
items.add("back to"+rootPath);
paths.add(rootPath);
//第二个设置为回到上一层
items.add("back to ../");
paths.add(files.getParent());
}
for(int i=0;i<files.length();i++){
File file = f[i];
items.add(file.getName());
paths.add(file.getPath());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.textview, items);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(paths.get(position));
if(file.canRead()){
if(file.isDirectory()){
getFileDir(paths.get(position));
}else{
Toast.makeText(MainActivity.this, "这是文件", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "权限不够", Toast.LENGTH_SHORT).show();
}
}
该博客展示了如何在Android应用中列出根目录(/)下的所有文件。通过创建List并使用File对象,遍历目录,将文件名和路径分别存储到items和paths列表中。点击列表项时,会检查文件是否可读,如果是目录则进入该目录,否则显示文件信息。
3073

被折叠的 条评论
为什么被折叠?



