android 列出根目录下面所有文件

该博客展示了如何在Android应用中列出根目录(/)下的所有文件。通过创建List并使用File对象,遍历目录,将文件名和路径分别存储到items和paths列表中。点击列表项时,会检查文件是否可读,如果是目录则进入该目录,否则显示文件信息。


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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值