Android File Manager

Source: Internet
Author: User
Tags file separator

Recently I wrote a file management project called deamo, which mainly provides file browsing, file directory creation, file deletion, and rename functions,

:

The details are as follows;

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. textui Ls; 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; impor T 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"; // file path private list <Map <string, object> items; // content adapter private simp Leadapter adapter; // backup file parent directory private file backfile = NULL; // current file directory private string currentpath = "/sdcard"; // whether the file is successfully deleted private Boolean flag; @ overrideprotected void oncreate (bundle savedinstancestate) {setcontentview (R. layout. files); settitle ("File Manager"); FileView = (listview) findviewbyid (R. id. filelist); listdir (PATH); super. oncreate (savedinstancestate);}/*** dynamically bind the file information to the listview * @ Param path */private void listdi R (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); //}/*** returns information about all file directories * @ 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) {// return to the/sdcard directory path = "/sdcard"; listdir (PATH );} else if (position = 1) {// return the top-level directory toparent ();} else {If (items! = NULL) {Path = (string) items. get (position ). get ("path"); 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 () {// return to the parent directory file = new file (PATH); file parent = file. getparentfile (); If (parent = NULL) {listdir (PATH);} else {Path = Parent. getabsolutepath (); listdir (PATH) ;}/ *** file operation prompt * @ Param ID */private void mydialog (int id) {alertdialog. 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 ("create folder"); builder. setview (textentryview); builder. setpositivebutton ("OK", new created Ialog (textentryview); builder. setnegativebutton ("cancel", null); break; Case 1: layoutinflater factory2 = layoutinflater. from (this); final view textentryview2 = factory2.inflate (R. layout. filedialog, null); builder. settitle ("rename a file"); builder. setview (textentryview2); builder. setpositivebutton ("OK", new renamedialog (textentryview2); builder. setnegativebutton ("cancel", null); break; Case 2: builder. settitle ("You are sure Are you sure you want to delete it? "); Builder. setpositivebutton ("OK", new deletedialog (); builder. setnegativebutton ("cancel", null); break;} builder. create (). show ();}/*** delete a specified directory or file based on the path, whether it exists or not * @ Param Spath the directory or file to be deleted * @ return returns true if the deletion is successful, otherwise, false is returned. */Public Boolean deletefolder (string Spath) {flag = false; file = new file (Spath); // determine whether a directory or file exists if (! File. exists () {// returns false return flag;} else {// determines whether it is a file if (file. isfile () {// return deletefile (Spath );} when else {// is a directory, call the delete directory method return deletedirectory (Spath );}}} /*** delete a single file * @ Param Spath File Name of the deleted file * @ return true if the deletion of a single file is successful; otherwise, false */Public Boolean deletefile (string Spath) is returned) {flag = false; file = new file (Spath); // Delete if (file. isfile () & file. exists () {File. delete (); flag = true;} return flag;}/*** Delete directory (folder) and the file in the directory * @ Param Spath is the file path of the deleted directory * @ return returns true if the directory is deleted successfully; otherwise, false */Public Boolean deletedirectory (string Spath) is returned) {// If Spath does not end with a file separator, the file separator if (! Spath. endswith (file. separator) {Spath = Spath + file. separator;} file dirfile = new file (Spath); // exit if (! Dirfile. exists () |! Dirfile. isdirectory () {return false;} flag = true; // delete all files in the folder (including subdirectories) file [] files = dirfile. listfiles (); For (INT I = 0; I <files. length; I ++) {// Delete the sub-file if (files [I]. isfile () {flag = deletefile (files [I]. getabsolutepath (); If (! Flag) break;} // Delete the subdirectory else {flag = deletedirectory (files [I]. getabsolutepath (); If (! Flag) break;} If (! Flag) return false; // Delete the current directory if (dirfile. delete () {return true;} else {return false;}/*** file refresh * @ Param file */private void filescan (string file) {uri data = Uri. parse ("file: //" + files); sendbroadcast (new intent (intent. action_media_scanner_scan_file, data);}/*** start file open * @ Param f */private void openfile (file F) {intent = new intent (); intent. addflags (intent. flag_activity_new_tas K); intent. setaction (Android. content. intent. action_view); // obtain the file media type string type = getmimetype (f); If (type = NULL) return; intent. setdataandtype (URI. fromfile (F), type); startactivity (intent);}/*** get file type * @ Param f * @ return */private string getmimetype (file F) {string type = ""; string filename = f. getname (); string end = filename. substring (filename. indexof (". ") + 1 ). tolowercase (); // determines the file type 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;} // The Mime Type format is "file type/file extension" type + = "/*"; return type ;} @ overridepublic Boolean oncreateoptionsmenu (menu) {menu. add (0, menu. first, 0, "creat file"); menu. add (0, menu. first + 1, 0, "about other"); Return Su Per. oncreateoptionsmenu (menu) ;}@ overridepublic Boolean onoptionsitemselected (menuitem item) {Switch (item. getitemid () {Case 1: mydialog (0); break; Case 2: Toast. maketext (this, "All Rights Reserved. Piracy is required! ", 500). Show (); break;} return Super. onoptionsitemselected (item) ;}@ overridepublic Boolean onitemlongclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {alertdialog. 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;} @ overridep Ublic 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 textentryvie W2; 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 diich, 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 () ;}/ *** file operation select * @ author administrator **/class longdialog implements dialoginterface. onclicklistener {private int Pos = 0; Public longdiener (int pos) {This. pos = POS ;}@ overridepublic void onclick (dialoginterface diich, 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 ;}}}}

Layout file files. XM file 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 file:

<?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>

By the way, do not forget to add permissions. If yes, an error may occur.

<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"/>

The above operations are performed on the SD card and are not applicable to system file management.

You can also use the. jar package provided by a third party for file management-related operations.

For example, the fileutils class of Apache commons is a tool class that greatly simplifies file operations.

1. Download jar address: http://commons.apache.org/proper/commons-io/download_io.cgi
2. Import the commons-io-2.4.jar file to your project

Related Articles: http://snkcxy.iteye.com/blog/1845862

The Code is a little long and can be understood slowly. If there are any deficiencies, please point out. Make progress together and learn together!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.