Android 文件管理器

最近写了一个文件管理deamo,主要功能文件浏览,新建文件目录,文件删除以及重命名相关功能,

效果图:










详细如下;

[java]  view plain copy
  1. package com.taskmanage.file;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.util.ArrayList;  
  6. import java.util.HashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import android.app.Activity;  
  11. import android.app.AlertDialog;  
  12. import android.content.DialogInterface;  
  13. import android.content.DialogInterface.OnClickListener;  
  14. import android.content.Intent;  
  15. import android.net.Uri;  
  16. import android.os.Bundle;  
  17. import android.text.TextUtils;  
  18. import android.util.Log;  
  19. import android.view.ContextMenu;  
  20. import android.view.ContextMenu.ContextMenuInfo;  
  21. import android.view.GestureDetector.OnGestureListener;  
  22. import android.view.LayoutInflater;  
  23. import android.view.Menu;  
  24. import android.view.MenuItem;  
  25. import android.view.MotionEvent;  
  26. import android.view.View;  
  27. import android.widget.AdapterView;  
  28. import android.widget.AdapterView.OnItemClickListener;  
  29. import android.widget.AdapterView.OnItemLongClickListener;  
  30. import android.widget.EditText;  
  31. import android.widget.ListView;  
  32. import android.widget.SimpleAdapter;  
  33. import android.widget.Toast;  
  34.   
  35. public class FileActivity extends Activity implements OnItemClickListener,OnItemLongClickListener{  
  36.   
  37.     private ListView fileview;  
  38.     private String path = "/sdcard";  
  39.     //文件路径  
  40.     private List<Map<String, Object>> items;  
  41.     //内容适配器  
  42.     private SimpleAdapter adapter;  
  43.     //备份文件父目录  
  44.     private File backFile=null;  
  45.     //当前文件目录  
  46.     private String currentPath="/sdcard";  
  47.     //文件是否成功删除  
  48.     private boolean flag;  
  49.       
  50.     @Override  
  51.     protected void onCreate(Bundle savedInstanceState) {  
  52.         setContentView(R.layout.files);  
  53.         setTitle("文件管理器");  
  54.         fileview = (ListView) findViewById(R.id.filelist);  
  55.         listDir(path);  
  56.           
  57.         super.onCreate(savedInstanceState);  
  58.     }  
  59.   
  60.     /** 
  61.      * 动态绑定文件信息到listview上 
  62.      * @param path 
  63.      */  
  64.     private void listDir(String path){  
  65.         items=bindList(path);  
  66.           
  67. //      if(items!=null){  
  68.             adapter = new SimpleAdapter(this, items, R.layout.file_row,  
  69.                     new String[] { "name""path" ,"img"}, new int[] { R.id.name,  
  70.                             R.id.desc ,R.id.img});  
  71.             fileview.setAdapter(adapter);  
  72.             fileview.setOnItemClickListener(this);  
  73.             fileview.setOnItemLongClickListener(this);  
  74.             fileview.setSelection(0);  
  75. //      }  
  76.     }  
  77.     /** 
  78.      * 返回所有文件目录信息 
  79.      * @param path 
  80.      * @return 
  81.      */  
  82.     private List<Map<String, Object>> bindList(String path){  
  83.         File[] files = new File(path).listFiles();  
  84. //      if(files!=null){  
  85.         List<Map<String, Object>> list= new ArrayList<Map<String, Object>>(files.length);  
  86.             Map<String, Object> root = new HashMap<String, Object>();  
  87.             root.put("name""/sdcard");  
  88.             root.put("img", R.drawable.file_root);  
  89.             root.put("path""root directory");  
  90.             list.add(root);  
  91.             Map<String, Object> pmap = new HashMap<String, Object>();  
  92.             pmap.put("name""back");  
  93.             pmap.put("img", R.drawable.file_paranet);  
  94.             pmap.put("path""paranet Directory");  
  95.             list.add(pmap);  
  96.             for (File file : files){  
  97.                 Map<String, Object> map = new HashMap<String, Object>();  
  98.                 if(file.isDirectory()){  
  99.                     map.put("img", R.drawable.directory);  
  100.                 }else{  
  101.                     map.put("img", R.drawable.file_doc);  
  102.                 }  
  103.                 map.put("name", file.getName());  
  104.                 map.put("path", file.getPath());  
  105.                 list.add(map);  
  106.             }  
  107.             return list;  
  108.         /*} 
  109.         return null;*/  
  110.     }  
  111.       
  112.     @Override  
  113.     public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {  
  114.           
  115.         if (position == 0) {//返回到/sdcard目录  
  116.             path = "/sdcard";  
  117.             listDir(path);  
  118.         }else if(position == 1){//返回上一级目录  
  119.             toParent();  
  120.         } else {  
  121.             if(items!=null){  
  122.             path = (String) items.get(position).get("path");  
  123.             File file = new File(path);  
  124.             if (file.canRead()&&file.canExecute()&&file.isDirectory()){  
  125.                 listDir(path);  
  126.             }  
  127.             else{  
  128.                 openFile(file);  
  129.                 Toast.makeText(this,"no dir",Toast.LENGTH_SHORT).show();  
  130.             }  
  131.            }  
  132.         }  
  133.         backFile=new File(path);  
  134.     }  
  135.       
  136.     private void toParent() {//回到父目录  
  137.         File file = new File(path);  
  138.         File parent = file.getParentFile();  
  139.         if(parent == null){  
  140.             listDir(path);    
  141.         }else{  
  142.             path = parent.getAbsolutePath();  
  143.             listDir(path);  
  144.         }  
  145.     }  
  146.     /** 
  147.      * 文件操作提示 
  148.      * @param id 
  149.      */  
  150.     private void Mydialog(int id){  
  151.           
  152.         AlertDialog.Builder builder=new AlertDialog.Builder(this);  
  153.           
  154.         switch(id){  
  155.         case 0:  
  156.              LayoutInflater factory = LayoutInflater.from(this);  
  157.                 final View textEntryView = factory.inflate(R.layout.filedialog, null);  
  158.                     builder.setTitle("创建文件夹");  
  159.                     builder.setView(textEntryView);  
  160.                     builder.setPositiveButton("确定"new CreateDialog(textEntryView));  
  161.                     builder.setNegativeButton("取消"null);  
  162.             break;  
  163.         case 1:  
  164.              LayoutInflater factory2 = LayoutInflater.from(this);  
  165.                 final View textEntryView2 = factory2.inflate(R.layout.filedialog, null);  
  166.                     builder.setTitle("重命名文件");  
  167.                     builder.setView(textEntryView2);  
  168.                     builder.setPositiveButton("确定"new RenameDialog(textEntryView2));  
  169.                     <span style="font-family: Arial, Helvetica, sans-serif;">builder.setNegativeButton("取消"null);</span>  
  170.   
  171.             break;  
  172.         case 2:  
  173.              builder.setTitle("你确定要删除吗?");  
  174.                 builder.setPositiveButton("确定"new DeleteDialog());  
  175.                 builder.setNegativeButton("取消"null);  
  176.             break;  
  177.         }  
  178.         builder.create().show();  
  179.     }  
  180.       
  181.     /** 
  182.      *  根据路径删除指定的目录或文件,无论存在与否 
  183.      *@param sPath  要删除的目录或文件 
  184.      *@return 删除成功返回 true,否则返回 false。 
  185.      */  
  186.     public boolean DeleteFolder(String sPath) {  
  187.         flag = false;  
  188.        File file = new File(sPath);  
  189.         // 判断目录或文件是否存在  
  190.         if (!file.exists()) {  // 不存在返回 false  
  191.             return flag;  
  192.         } else {  
  193.             // 判断是否为文件  
  194.             if (file.isFile()) {  // 为文件时调用删除文件方法  
  195.                 return deleteFile(sPath);  
  196.             } else {  // 为目录时调用删除目录方法  
  197.                 return deleteDirectory(sPath);  
  198.             }  
  199.         }  
  200.     }  
  201.     /** 
  202.      * 删除单个文件 
  203.      * @param   sPath    被删除文件的文件名 
  204.      * @return 单个文件删除成功返回true,否则返回false 
  205.      */  
  206.     public boolean deleteFile(String sPath) {  
  207.         flag = false;  
  208.         File file = new File(sPath);  
  209.         // 路径为文件且不为空则进行删除  
  210.         if (file.isFile() && file.exists()) {  
  211.             file.delete();  
  212.             flag = true;  
  213.         }  
  214.         return flag;  
  215.     }  
  216.     /** 
  217.      * 删除目录(文件夹)以及目录下的文件 
  218.      * @param   sPath 被删除目录的文件路径 
  219.      * @return  目录删除成功返回true,否则返回false 
  220.      */  
  221.     public boolean deleteDirectory(String sPath) {  
  222.         //如果sPath不以文件分隔符结尾,自动添加文件分隔符  
  223.         if (!sPath.endsWith(File.separator)) {  
  224.             sPath = sPath + File.separator;  
  225.         }  
  226.         File dirFile = new File(sPath);  
  227.         //如果dir对应的文件不存在,或者不是一个目录,则退出  
  228.         if (!dirFile.exists() || !dirFile.isDirectory()) {  
  229.             return false;  
  230.         }  
  231.         flag = true;  
  232.         //删除文件夹下的所有文件(包括子目录)  
  233.         File[] files = dirFile.listFiles();  
  234.         for (int i = 0; i < files.length; i++) {  
  235.             //删除子文件  
  236.             if (files[i].isFile()) {  
  237.                 flag = deleteFile(files[i].getAbsolutePath());  
  238.                 if (!flag) break;  
  239.             } //删除子目录  
  240.             else {  
  241.                 flag = deleteDirectory(files[i].getAbsolutePath());  
  242.                 if (!flag) break;  
  243.             }  
  244.         }  
  245.         if (!flag) return false;  
  246.         //删除当前目录  
  247.         if (dirFile.delete()) {  
  248.             return true;  
  249.         } else {  
  250.             return false;  
  251.         }  
  252.     }  
  253.     /** 
  254.      * 文件刷新 
  255.      * @param file 
  256.      */  
  257.     private void fileScan(String file){      
  258.         Uri data = Uri.parse("file://"+file);      
  259.               
  260.         sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));      
  261.     }      
  262.       
  263.     /** 
  264.      * 启动文件打开  
  265.      * @param f 
  266.      */  
  267.     private void openFile(File f) {    
  268.         Intent intent = new Intent();    
  269.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
  270.         intent.setAction(android.content.Intent.ACTION_VIEW);    
  271.             
  272.         // 获取文件媒体类型    
  273.         String type = getMIMEType(f);    
  274.         if(type==null)  
  275.             return;  
  276.         intent.setDataAndType(Uri.fromFile(f), type);    
  277.         startActivity(intent);    
  278.     }    
  279.   /** 
  280.    * 获取文件类型  
  281.    * @param f 
  282.    * @return 
  283.    */  
  284.     private String getMIMEType(File f) {    
  285.         String type = "";    
  286.         String fileName = f.getName();    
  287.         String end = fileName.substring(fileName.indexOf(".") + 1).toLowerCase();    
  288.         // 判断文件类型    
  289.         if(end.equals("wma") || end.equals("mp3") || end.equals("midi")||end.equals("ape")     
  290.                 || end.equals("amr") || end.equals("ogg") || end.equals("wav")||end.equals("acc")) {    
  291.             type = "audio";     
  292.         } else if (end.equals("3gp") || end.equals("mp4")||end.equals("rmvb")||end.equals("flv")  
  293.                 ||end.equals("avi")||end.equals("wmv")||end.equals("f4v")) {    
  294.             type = "video";    
  295.         } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")     
  296.                 || end.equals("jpeg") || end.equals("bmp")) {    
  297.             type = "image";    
  298.         } else {    
  299.           Toast.makeText(getApplicationContext(), "not media file", Toast.LENGTH_LONG).show();  
  300.           return null;  
  301.         }    
  302.         // MIME Type格式是"文件类型/文件扩展名"    
  303.         type += "/*";    
  304.         return type;    
  305.     }  
  306.   
  307.     @Override  
  308.     public boolean onCreateOptionsMenu(Menu menu) {  
  309.           
  310.         menu.add(0, Menu.FIRST, 0"creat file");  
  311.         menu.add(0, Menu.FIRST+10"about other");  
  312.           
  313.         return super.onCreateOptionsMenu(menu);  
  314.     }  
  315.       
  316.     @Override  
  317.     public boolean onOptionsItemSelected(MenuItem item) {  
  318.         switch (item.getItemId()) {    
  319.         case 1:  
  320.             Mydialog(0);  
  321.             break;  
  322.         case 2:  
  323.             Toast.makeText(this"版权所有,盗版必究!"500).show();  
  324.             break;  
  325.         }  
  326.         return super.onOptionsItemSelected(item);  
  327.     }  
  328.       
  329.     @Override  
  330.     public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,  
  331.             long arg3) {  
  332.         AlertDialog.Builder builder=new AlertDialog.Builder(this);  
  333.           
  334.         String[] items={"rename file","delete file"};  
  335.           
  336.         builder.setItems(items, new LongDialog(arg2));  
  337.         builder.create().show();  
  338.         return true;  
  339.     }  
  340.       
  341.     class CreateDialog implements DialogInterface.OnClickListener{  
  342.   
  343.         private View textEntryView;  
  344.   
  345.         public CreateDialog(View textEntryView) {  
  346.             this.textEntryView = textEntryView;  
  347.         }  
  348.   
  349.         @Override  
  350.         public void onClick(DialogInterface dialog, int which) {  
  351.   
  352.             EditText userName = (EditText) textEntryView.findViewById(R.id.fname);  
  353.             String fn=userName.getText().toString().trim();  
  354.               
  355.             if(!TextUtils.isEmpty(fn)){  
  356.                 File f=new File(backFile,fn);  
  357.                 if(f.exists()){  
  358.                     Toast.makeText(FileActivity.this"file has exist"500).show();  
  359.                 }else{  
  360.                     Toast.makeText(FileActivity.this"file creat "+f.mkdir(), 500).show();  
  361.                     listDir(f.getAbsolutePath());  
  362.                 //  fileScan(f.getAbsolutePath());  
  363.                     adapter.notifyDataSetChanged();  
  364.                 }  
  365.             }  
  366.         }  
  367.     }  
  368.       
  369.     class RenameDialog implements DialogInterface.OnClickListener{  
  370.         private View textEntryView2;  
  371.   
  372.         public RenameDialog(View textEntryView2) {  
  373.             this.textEntryView2 = textEntryView2;  
  374.         }  
  375.         @Override  
  376.         public void onClick(DialogInterface dialog, int which) {  
  377.             EditText userName = (EditText) textEntryView2.findViewById(R.id.fname);  
  378.             String fn=userName.getText().toString().trim();  
  379.               
  380.             if(!TextUtils.isEmpty(fn)){  
  381.                 File old=new File(currentPath);  
  382.                 File f=new File(backFile.getAbsolutePath(),fn);  
  383.                 if(f.exists()){  
  384.                     Toast.makeText(FileActivity.this"file has exist"500).show();  
  385.                 }else{  
  386.                     Toast.makeText(FileActivity.this"file rename "+old.renameTo(f), 500).show();  
  387.                     listDir(f.getAbsolutePath());  
  388.             //      fileScan(f.getAbsolutePath());  
  389.                     adapter.notifyDataSetChanged();  
  390.                 }  
  391.             }  
  392.         }  
  393.     }  
  394.     class DeleteDialog implements DialogInterface.OnClickListener{  
  395.   
  396.         @Override  
  397.         public void onClick(DialogInterface dialog, int which) {  
  398.             File f=new File(currentPath);  
  399.             if(f.exists()){  
  400.                 DeleteFolder(f.getAbsolutePath());  
  401.             listDir(f.getParent());  
  402.        //   fileScan(f.getAbsolutePath());  
  403.             adapter.notifyDataSetChanged();  
  404.             }  
  405.             else  
  406.                 Toast.makeText(FileActivity.this"file not exist"500).show();  
  407.         }  
  408.     }  
  409.     /**  
  410.      * 文件操作选择  
  411.      * @author Administrator  
  412.      *  
  413.      */  
  414.     class LongDialog implements DialogInterface.OnClickListener{  
  415.         private int pos=0;  
  416.           
  417.         public LongDialog(int pos){  
  418.             this.pos=pos;  
  419.         }  
  420.         @Override  
  421.         public void onClick(DialogInterface dialog, int which) {  
  422.             switch(which){  
  423.             case 0:  
  424.                 currentPath = (String) items.get(pos).get("path");  
  425.                 Mydialog(1);  
  426.                 break;  
  427.             case 1:  
  428.                 currentPath = (String) items.get(pos).get("path");  
  429.                 Mydialog(2);  
  430.                 break;  
  431.             }  
  432.         }  
  433.     }  
  434.       
  435. }  


布局文件files.xm文件l:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.   
  6.     <ListView   
  7.         android:layout_width="fill_parent"  
  8.         android:layout_height="fill_parent"   
  9.         android:id="@+id/filelist" />  
  10. </LinearLayout>  


file_row.xml文件:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:id="@+id/vw1"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="wrap_content"  
  7.     android:orientation="horizontal">      
  8.   
  9.     <ImageView android:id="@+id/img"  
  10.         android:layout_width="32dip"  
  11.         android:layout_margin="4dip"  
  12.         android:layout_height="32dip"/>  
  13.    
  14.    <LinearLayout  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:orientation="vertical">  
  18.   
  19.         <TextView android:id="@+id/name"  
  20.             android:textSize="18sp"  
  21.             android:textStyle="bold"  
  22.             android:layout_width="fill_parent"  
  23.             android:layout_height="wrap_content"/>  
  24.   
  25.         <TextView android:id="@+id/desc"  
  26.             android:textSize="14sp"  
  27.             android:layout_width="fill_parent"  
  28.             android:paddingLeft="10dip"  
  29.             android:layout_height="wrap_content"/>  
  30.   
  31.     </LinearLayout>  
  32.   
  33. </LinearLayout>  


对了,最后别忘了加权限,要不可会报错的

[html]  view plain copy
  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   
  2. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>   
  3. <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


代码有点长,慢慢看都能理解,如有不足,还请指出。共同进步,共同学习!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值