最近寫了一個檔案管理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;@Overrideprotected 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;*/}@Overridepublic 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)); builder.setNegativeButton("取消", null);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; } @Overridepublic 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);}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) { case 1:Mydialog(0);break;case 2:Toast.makeText(this, "著作權,盜版必究!", 500).show();break;}return super.onOptionsItemSelected(item);}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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{@Overridepublic 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;}@Overridepublic 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>
file_row.xml檔案:
<?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
代碼有點長,慢慢看都能理解,如有不足,還請指出。共同進步,共同學習!