我们在遍历文件夹的时候由于涉及到SD卡相关操作,所以我们需要添加如下权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

首先,需要检查SD卡挂载状态:

	boolean sdCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (!sdCard) {
Toast.makeText(MainActivity.this, "SD卡未挂载", Toast.LENGTH_SHORT).show();
MainActivity.this.finish();
}

当getExternalStorageState()挂载状态返回为未挂载时,程序提示错误,并结束执行。

然后,通过Intent获取Activity当前的消息,如果第一次执行,那么Intent所get到的信息为空。此时就读取SD卡根目录文件列表。如果不是第一次执行,那么就获取上次传入的文件路径信息,然后再读取此文件路径下的文件列表。

       Intent intent = getIntent();
CharSequence cs = intent.getCharSequenceExtra("filePath"); //filePath 为传入的文件路径信息
if (cs != null) {
File file = new File(cs.toString());
tvPath.setText(file.getPath());
files = file.listFiles();
} else {
File sdFile = Environment.getExternalStorageDirectory();
tvPath.setText(sdFile.getPath());
files = sdFile.listFiles();
}ra("filePath");

然后,在获取到了所有的文件列表信息之后,我们需要将其输入到ListView中,而ListView数据是和Adapter绑定的。Adapter的初始化原型为:

SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
// context 是上下文,这里我们取MainActivity.this
// data 是数据来源,是一个Map结构,最终显示Map中的Value
// resource 是资源文件,根据此xml文件将ListView中内容排版
// from 是数据来源的名称,为Map中的Key值
// to 是将数据和resource中进行绑定id的值

根据此,我们实例化一个Map来存储最终需要显示的数据,同时新建一个资源文件/res/layout/list_layout.xml来对ListView内容进行排版:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"> <ImageView
android:layout_width="46dp"
android:layout_height="45dp"
android:id="@+id/image" /> <TextView
android:layout_width="wrap_content"
android:layout_height="38dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/fileName"
android:layout_weight="0.14" />
</LinearLayout>
	List<HashMap<String, Object>> list = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
HashMap<String, Object> hashMap = new HashMap<>();
if (files[i].isDirectory()) {
hashMap.put("image", android.R.drawable.ic_dialog_email);
} else {
hashMap.put("image", android.R.drawable.ic_dialog_map);
}
hashMap.put("fileName", files[i].getName());
list.add(hashMap);
}

最后,实例化此Adapter并将ListView与其绑定,同时为ListView添加Item单击事件。如果Item是目录的话,就将目录的路径通过intent传递给Activity,然后启动此Activity。回到起始定义Intent的地方,此Intent会得到由Activity传递过来的目录信息,然后根据此目录信息可以进一步访问文件目录。

        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.list_layout,
new String[]{"image", "fileName"}, new int[]{R.id.image, R.id.fileName});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (files[i].isDirectory()) {
File[] childFile = files[i].listFiles();
if (childFile != null && childFile.length >= 0) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("filePath", files[i].getPath());
Toast.makeText(MainActivity.this, files[i].getPath(), Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
}
});

完整代码如下:

import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast; import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; public class MainActivity extends AppCompatActivity { private TextView tvPath;
private ListView listView;
private File[] files; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tvPath = (TextView) findViewById(R.id.textView);
listView = (ListView) findViewById(R.id.listView); boolean sdCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (!sdCard) {
Toast.makeText(MainActivity.this, "SD卡未挂载", Toast.LENGTH_SHORT).show();
MainActivity.this.finish();
} Intent intent = getIntent();
CharSequence cs = intent.getCharSequenceExtra("filePath");
if (cs != null) {
File file = new File(cs.toString());
tvPath.setText(file.getPath());
files = file.listFiles();
} else {
File sdFile = Environment.getExternalStorageDirectory();
tvPath.setText(sdFile.getPath());
files = sdFile.listFiles();
} List<HashMap<String, Object>> list = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
HashMap<String, Object> hashMap = new HashMap<>();
if (files[i].isDirectory()) {
hashMap.put("image", android.R.drawable.ic_dialog_email);
} else {
hashMap.put("image", android.R.drawable.ic_dialog_map);
}
hashMap.put("fileName", files[i].getName());
list.add(hashMap);
} SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.list_layout,
new String[]{"image", "fileName"}, new int[]{R.id.image, R.id.fileName});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (files[i].isDirectory()) {
File[] childFile = files[i].listFiles();
if (childFile != null && childFile.length >= 0) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("filePath", files[i].getPath());
Toast.makeText(MainActivity.this, files[i].getPath(), Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
}
}); } }

Android开发手记(21) 遍历文件夹的更多相关文章

  1. Windows下C++遍历文件夹中的文件

    Windows下,在VS中开发,C++遍历文件夹下文件. 在Windows下,遍历文件所用到的函数和结构体,需要在程序中包含头文件#include <io.h>,在VS中,头文件io.h实 ...

  2. 写个批处理脚本来帮忙干活--遍历文件夹&字符串处理

    这次打算写几篇关于脚本方面的博客,主要是记录一下 Gradle 脚本和批处理脚本的一些写法,方便后续查阅. 前言 平常开发过程中,一些较为重复的手工性工作,如果能让脚本来帮忙处理,自然是最好的,刚好之 ...

  3. 个人永久性免费-Excel催化剂功能第83波-遍历文件夹内文件信息特别是图像、音视频等特有信息

    在过往的功能中,有体现出在Excel上管理文件的极大优势,在文件的信息元数据中,有图片和音视频这两类特有的属性数据,此篇对过往功能的一个补充,特别增加了图片和音视频信息的遍历功能. 使用场景 在文件管 ...

  4. C#遍历文件夹下所有文件

    FolderForm.cs的代码如下: using System; using System.Collections.Generic; using System.Diagnostics; using ...

  5. C#遍历文件夹及文件

    背景: 想自己实现一个网盘系统,于是需要用到遍历文件(夹)操作. C#基本知识梳理: 1.如何获取指定目录包含的文件和子目录 (1). DirectoryInfo.GetFiles():获取目录中(不 ...

  6. linux c遍历文件夹 和文件查找的方法

    linux c遍历文件夹的方法比较简单,使用c来实现 #include <iostream> #include <stdio.h> #include <sys/types ...

  7. PHPCMS V9二次开发便捷自定义后台入口文件夹

    phpcms v9二次开发便捷自定义后台入口文件夹 最新发布的phpcms v9由于采用了mvc的设计模式,所以它的后台访问地址是固定的,虽然可以通过修改路由配置文件来实现修改,但每次都修改路由配置文 ...

  8. Android开发之获取xml文件的输入流对象

    介绍两种Android开发中获取xml文件的输入流对象 第一种:通过assets目录获取 1.首先是在Project下app/src/main目录下创建一个assets文件夹,将需要获取的xml文件放 ...

  9. windowsAPI遍历文件夹(速度高于递归)

    #region API 遍历文件夹及其子文件夹和子文件 #region 声明WIN32API函数以及结构 ************************************** [DllImpo ...

随机推荐

  1. c# appdomain

    http://www.cnblogs.com/Terrylee/archive/2005/11/28/285809.html

  2. Entity Framework OData filter inherit

    过滤继承对象 TPH 的情况 EF : return Task.FromResult<IQueryable<Parent>>( query.OfType<ChildA&g ...

  3. Unity 网络斗地主 判断牌的类型

    Unity 网络斗地主  牌的类型 web版本演示地址:   http://www.dreamhome666.com/Desktop.html 在上个版本中,下面的角色在牌的后面,可以将角色做为一个P ...

  4. db2中修改表字段的长度,查看表字段长度,以及查看表字段已存放值大小

    修改表字段语句: alter table 表名 alter column  字段名 set data type varchar(7700) 如: ALTER TABLE JV_BI_BACK_OPER ...

  5. VC版本的MakeObjectInstance把WNDPROC映射到类的成员函数

    这段时间用VC封装Windows类库,没有MakeObjectInstance处理窗口消息确实不爽,又不想使用MFC的消息映射,这玩意的效率和美观只能呵呵. 至于MakeObjectInstance是 ...

  6. Struts2 实现分页

    1.转自:http://www.cnblogs.com/shiyangxt/archive/2008/11/04/1316737.html环境:MyEclipse6.5+Mysql5+struts2. ...

  7. POJ 2762 Going from u to v or from v to u?(强联通 + TopSort)

    题目大意: 为了锻炼自己的儿子 Jiajia 和Wind 把自己的儿子带入到一个洞穴内,洞穴有n个房间,洞穴的道路是单向的. 每一次Wind 选择两个房间  x 和 y,   让他的儿子从一个房间走到 ...

  8. 【转】Android Recovery模式

    原文网址:http://leox.iteye.com/blog/975303 (muddogxp 原创,转载请注明) Recovery简介 Android利用Recovery模式,进行恢复出厂设置,O ...

  9. 2015第37周二foxmail邮箱客户端迁移

    foxmail7.0邮箱客户端迁移风波浪费我下午不少时间,不知为何做完foxmail客户端在卡的时候我将其强制关闭,然后将整个邮箱目录拷贝到一台新电脑上,运行客户端居然我要新建账户(账户信息丢失),将 ...

  10. 数据结构(树链剖分):BZOJ 4034: [HAOI2015]T2

    Description 有一棵点数为 N 的树,以点 1 为根,且树点有边权.然后有 M 个 操作,分为三种: 操作 1 :把某个节点 x 的点权增加 a . 操作 2 :把某个节点 x 为根的子树中 ...