最近写了一个文件管理deamo,主要功能文件浏览,新建文件目录,文件删除以及重命名相关功能,
效果图:
详细如下;
- package com.taskmanage.file;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.content.DialogInterface.OnClickListener;
- import android.content.Intent;
- import android.net.Uri;
- import android.os.Bundle;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.ContextMenu;
- import android.view.ContextMenu.ContextMenuInfo;
- import android.view.GestureDetector.OnGestureListener;
- import android.view.LayoutInflater;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.MotionEvent;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.AdapterView.OnItemLongClickListener;
- import android.widget.EditText;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.Toast;
- public class FileActivity extends Activity implements OnItemClickListener,OnItemLongClickListener{
- private ListView fileview;
- private String path = "/sdcard";
- //文件路径
- private List<Map<String, Object>> items;
- //内容适配器
- private SimpleAdapter adapter;
- //备份文件父目录
- private File backFile=null;
- //当前文件目录
- private String currentPath="/sdcard";
- //文件是否成功删除
- private boolean flag;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.files);
- setTitle("文件管理器");
- fileview = (ListView) findViewById(R.id.filelist);
- listDir(path);
- super.onCreate(savedInstanceState);
- }
- /**
- * 动态绑定文件信息到listview上
- * @param path
- */
- private void listDir(String path){
- items=bindList(path);
- // if(items!=null){
- adapter = new SimpleAdapter(this, items, R.layout.file_row,
- new String[] { "name", "path" ,"img"}, new int[] { R.id.name,
- R.id.desc ,R.id.img});
- fileview.setAdapter(adapter);
- fileview.setOnItemClickListener(this);
- fileview.setOnItemLongClickListener(this);
- fileview.setSelection(0);
- // }
- }
- /**
- * 返回所有文件目录信息
- * @param path
- * @return
- */
- private List<Map<String, Object>> bindList(String path){
- File[] files = new File(path).listFiles();
- // if(files!=null){
- List<Map<String, Object>> list= new ArrayList<Map<String, Object>>(files.length);
- Map<String, Object> root = new HashMap<String, Object>();
- root.put("name", "/sdcard");
- root.put("img", R.drawable.file_root);
- root.put("path", "root directory");
- list.add(root);
- Map<String, Object> pmap = new HashMap<String, Object>();
- pmap.put("name", "back");
- pmap.put("img", R.drawable.file_paranet);
- pmap.put("path", "paranet Directory");
- list.add(pmap);
- for (File file : files){
- Map<String, Object> map = new HashMap<String, Object>();
- if(file.isDirectory()){
- map.put("img", R.drawable.directory);
- }else{
- map.put("img", R.drawable.file_doc);
- }
- map.put("name", file.getName());
- map.put("path", file.getPath());
- list.add(map);
- }
- return list;
- /*}
- return null;*/
- }
- @Override
- public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
- if (position == 0) {//返回到/sdcard目录
- path = "/sdcard";
- listDir(path);
- }else if(position == 1){//返回上一级目录
- toParent();
- } else {
- if(items!=null){
- path = (String) items.get(position).get("path");
- File file = new File(path);
- if (file.canRead()&&file.canExecute()&&file.isDirectory()){
- listDir(path);
- }
- else{
- openFile(file);
- Toast.makeText(this,"no dir",Toast.LENGTH_SHORT).show();
- }
- }
- }
- backFile=new File(path);
- }
- private void toParent() {//回到父目录
- File file = new File(path);
- File parent = file.getParentFile();
- if(parent == null){
- listDir(path);
- }else{
- path = parent.getAbsolutePath();
- listDir(path);
- }
- }
- /**
- * 文件操作提示
- * @param id
- */
- private void Mydialog(int id){
- AlertDialog.Builder builder=new AlertDialog.Builder(this);
- switch(id){
- case 0:
- LayoutInflater factory = LayoutInflater.from(this);
- final View textEntryView = factory.inflate(R.layout.filedialog, null);
- builder.setTitle("创建文件夹");
- builder.setView(textEntryView);
- builder.setPositiveButton("确定", new CreateDialog(textEntryView));
- builder.setNegativeButton("取消", null);
- break;
- case 1:
- LayoutInflater factory2 = LayoutInflater.from(this);
- final View textEntryView2 = factory2.inflate(R.layout.filedialog, null);
- builder.setTitle("重命名文件");
- builder.setView(textEntryView2);
- builder.setPositiveButton("确定", new RenameDialog(textEntryView2));
- <span style="font-family: Arial, Helvetica, sans-serif;">builder.setNegativeButton("取消", null);</span>
- break;
- case 2:
- builder.setTitle("你确定要删除吗?");
- builder.setPositiveButton("确定", new DeleteDialog());
- builder.setNegativeButton("取消", null);
- break;
- }
- builder.create().show();
- }
- /**
- * 根据路径删除指定的目录或文件,无论存在与否
- *@param sPath 要删除的目录或文件
- *@return 删除成功返回 true,否则返回 false。
- */
- public boolean DeleteFolder(String sPath) {
- flag = false;
- File file = new File(sPath);
- // 判断目录或文件是否存在
- if (!file.exists()) { // 不存在返回 false
- return flag;
- } else {
- // 判断是否为文件
- if (file.isFile()) { // 为文件时调用删除文件方法
- return deleteFile(sPath);
- } else { // 为目录时调用删除目录方法
- return deleteDirectory(sPath);
- }
- }
- }
- /**
- * 删除单个文件
- * @param sPath 被删除文件的文件名
- * @return 单个文件删除成功返回true,否则返回false
- */
- public boolean deleteFile(String sPath) {
- flag = false;
- File file = new File(sPath);
- // 路径为文件且不为空则进行删除
- if (file.isFile() && file.exists()) {
- file.delete();
- flag = true;
- }
- return flag;
- }
- /**
- * 删除目录(文件夹)以及目录下的文件
- * @param sPath 被删除目录的文件路径
- * @return 目录删除成功返回true,否则返回false
- */
- public boolean deleteDirectory(String sPath) {
- //如果sPath不以文件分隔符结尾,自动添加文件分隔符
- if (!sPath.endsWith(File.separator)) {
- sPath = sPath + File.separator;
- }
- File dirFile = new File(sPath);
- //如果dir对应的文件不存在,或者不是一个目录,则退出
- if (!dirFile.exists() || !dirFile.isDirectory()) {
- return false;
- }
- flag = true;
- //删除文件夹下的所有文件(包括子目录)
- File[] files = dirFile.listFiles();
- for (int i = 0; i < files.length; i++) {
- //删除子文件
- if (files[i].isFile()) {
- flag = deleteFile(files[i].getAbsolutePath());
- if (!flag) break;
- } //删除子目录
- else {
- flag = deleteDirectory(files[i].getAbsolutePath());
- if (!flag) break;
- }
- }
- if (!flag) return false;
- //删除当前目录
- if (dirFile.delete()) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * 文件刷新
- * @param file
- */
- private void fileScan(String file){
- Uri data = Uri.parse("file://"+file);
- sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
- }
- /**
- * 启动文件打开
- * @param f
- */
- private void openFile(File f) {
- Intent intent = new Intent();
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setAction(android.content.Intent.ACTION_VIEW);
- // 获取文件媒体类型
- String type = getMIMEType(f);
- if(type==null)
- return;
- intent.setDataAndType(Uri.fromFile(f), type);
- startActivity(intent);
- }
- /**
- * 获取文件类型
- * @param f
- * @return
- */
- private String getMIMEType(File f) {
- String type = "";
- String fileName = f.getName();
- String end = fileName.substring(fileName.indexOf(".") + 1).toLowerCase();
- // 判断文件类型
- if(end.equals("wma") || end.equals("mp3") || end.equals("midi")||end.equals("ape")
- || end.equals("amr") || end.equals("ogg") || end.equals("wav")||end.equals("acc")) {
- type = "audio";
- } else if (end.equals("3gp") || end.equals("mp4")||end.equals("rmvb")||end.equals("flv")
- ||end.equals("avi")||end.equals("wmv")||end.equals("f4v")) {
- type = "video";
- } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
- || end.equals("jpeg") || end.equals("bmp")) {
- type = "image";
- } else {
- Toast.makeText(getApplicationContext(), "not media file", Toast.LENGTH_LONG).show();
- return null;
- }
- // MIME Type格式是"文件类型/文件扩展名"
- type += "/*";
- return type;
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- menu.add(0, Menu.FIRST, 0, "creat file");
- menu.add(0, Menu.FIRST+1, 0, "about other");
- return super.onCreateOptionsMenu(menu);
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case 1:
- Mydialog(0);
- break;
- case 2:
- Toast.makeText(this, "版权所有,盗版必究!", 500).show();
- break;
- }
- return super.onOptionsItemSelected(item);
- }
- @Override
- public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- AlertDialog.Builder builder=new AlertDialog.Builder(this);
- String[] items={"rename file","delete file"};
- builder.setItems(items, new LongDialog(arg2));
- builder.create().show();
- return true;
- }
- class CreateDialog implements DialogInterface.OnClickListener{
- private View textEntryView;
- public CreateDialog(View textEntryView) {
- this.textEntryView = textEntryView;
- }
- @Override
- public void onClick(DialogInterface dialog, int which) {
- EditText userName = (EditText) textEntryView.findViewById(R.id.fname);
- String fn=userName.getText().toString().trim();
- if(!TextUtils.isEmpty(fn)){
- File f=new File(backFile,fn);
- if(f.exists()){
- Toast.makeText(FileActivity.this, "file has exist", 500).show();
- }else{
- Toast.makeText(FileActivity.this, "file creat "+f.mkdir(), 500).show();
- listDir(f.getAbsolutePath());
- // fileScan(f.getAbsolutePath());
- adapter.notifyDataSetChanged();
- }
- }
- }
- }
- class RenameDialog implements DialogInterface.OnClickListener{
- private View textEntryView2;
- public RenameDialog(View textEntryView2) {
- this.textEntryView2 = textEntryView2;
- }
- @Override
- public void onClick(DialogInterface dialog, int which) {
- EditText userName = (EditText) textEntryView2.findViewById(R.id.fname);
- String fn=userName.getText().toString().trim();
- if(!TextUtils.isEmpty(fn)){
- File old=new File(currentPath);
- File f=new File(backFile.getAbsolutePath(),fn);
- if(f.exists()){
- Toast.makeText(FileActivity.this, "file has exist", 500).show();
- }else{
- Toast.makeText(FileActivity.this, "file rename "+old.renameTo(f), 500).show();
- listDir(f.getAbsolutePath());
- // fileScan(f.getAbsolutePath());
- adapter.notifyDataSetChanged();
- }
- }
- }
- }
- class DeleteDialog implements DialogInterface.OnClickListener{
- @Override
- public void onClick(DialogInterface dialog, int which) {
- File f=new File(currentPath);
- if(f.exists()){
- DeleteFolder(f.getAbsolutePath());
- listDir(f.getParent());
- // fileScan(f.getAbsolutePath());
- adapter.notifyDataSetChanged();
- }
- else
- Toast.makeText(FileActivity.this, "file not exist", 500).show();
- }
- }
- /**
- * 文件操作选择
- * @author Administrator
- *
- */
- class LongDialog implements DialogInterface.OnClickListener{
- private int pos=0;
- public LongDialog(int pos){
- this.pos=pos;
- }
- @Override
- public void onClick(DialogInterface dialog, int which) {
- switch(which){
- case 0:
- currentPath = (String) items.get(pos).get("path");
- Mydialog(1);
- break;
- case 1:
- currentPath = (String) items.get(pos).get("path");
- Mydialog(2);
- break;
- }
- }
- }
- }
布局文件files.xm文件l:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:id="@+id/filelist" />
- </LinearLayout>
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/vw1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal">
- <ImageView android:id="@+id/img"
- android:layout_width="32dip"
- android:layout_margin="4dip"
- android:layout_height="32dip"/>
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <TextView android:id="@+id/name"
- android:textSize="18sp"
- android:textStyle="bold"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
- <TextView android:id="@+id/desc"
- android:textSize="14sp"
- android:layout_width="fill_parent"
- android:paddingLeft="10dip"
- android:layout_height="wrap_content"/>
- </LinearLayout>
- </LinearLayout>
对了,最后别忘了加权限,要不可会报错的
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
以上都是在sd卡上的操作,不适用系统文件管理。
基于文件管理相关操作还可以使用第三方提供的.jar包操作
例如:apache的commons的FileUtils类就是这样一个工具类,使用它能大大的简化我们对文件的操作。
1.下载jar 地址:http://commons.apache.org/proper/commons-io/download_io.cgi
2.把commons-io-2.4.jar 这个文件导入到你的项目中
相关文章:http://snkcxy.iteye.com/blog/1845862
代码有点长,慢慢看都能理解,如有不足,还请指出。共同进步,共同学习!