public class Test_ListFile extends ListActivity { /** Called when the activity is first created. */ private List<String> items = null;//存放名称 private List<String> paths = null;//存放路径 private String rootPath = "/"; private TextView tv;
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) this.findViewById(R.id.TextView); this.getFileDir(rootPath);//获取rootPath目录下的文件. }
public void getFileDir(String filePath) { try{ this.tv.setText("当前路径:"+filePath);// 设置当前所在路径 items = new ArrayList<String>(); paths = new ArrayList<String>(); File f = new File(filePath); File[] files = f.listFiles();// 列出所有文件 // 如果不是根目录,则列出返回根目录和上一目录选项 if (!filePath.equals(rootPath)) { items.add("返回根目录"); paths.add(rootPath); items.add("返回上一层目录"); paths.add(f.getParent()); } // 将所有文件存入list中 if(files != null){ int count = files.length;// 文件个数 for (int i = 0; i < count; i++) { File file = files[i]; items.add(file.getName()); paths.add(file.getPath()); } }