Xiaomi Open source File Manager micodefileexplorer-Source Research (3)-most used tool class Util

Source: Internet
Author: User
Tags dateformat

Util.java, the most widely used ~
Many places in the code, have written a note description ~ Basic No need to explain ~
Package Net.micode.fileexplorer.util;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.filenamefilter;import Java.io.ioexception;import Java.text.dateformat;import Java.util.arraylist;import Java.util.Date;import Java.util.hashset;import Net.micode.fileexplorer.fileviewactivity;import net.micode.fileexplorer.GlobalConsts; Import Net.micode.fileexplorer.r;import Net.micode.fileexplorer.model.favoriteitem;import Net.micode.fileexplorer.model.fileinfo;import Android.app.notification;import Android.app.NotificationManager; Import Android.app.pendingintent;import Android.content.context;import Android.content.intent;import Android.content.pm.applicationinfo;import Android.content.pm.packageinfo;import Android.content.pm.packagemanager;import Android.graphics.drawable.drawable;import Android.os.Environment;import Android.util.log;import Android.view.actionmode;import Android.view.view;import Android.widget.TexThe tview;/** tool class, which contains many common tool methods, is called by many classes in the project. */public class Util {//This folder is stored in a APP2SD folder, which is the cache folder for all applications installed on your phone to the SD card.    Can I delete the Androidsecure folder? If the software does not work properly after deletion, it is not related to the system. Deletion of the words may result in damage to the program that moves to the SD card, data loss, and will not cause any serious consequences. As long as the mobile to the SD card damaged program Uninstall, reinstall, the phone is completely undamaged, the folder will be re-APP2SD when the automatic reconstruction.    private static String android_secure = "/mnt/sdcard/.android_secure"; Android.util.Log.log the 1th parameter, using "tag", and log4j in Logger.getlogger (GetClass ()) usage is not quite the same as private static final String Log_tag = " Util ";//Get SD card storage status," mounted "means ready public static Boolean Issdcardready () {return environment.getexternalstoragestate (). Equals (environment.media_mounted);} If path1 contains Path2public static Boolean Containspath (String path1, String path2) {String path = Path2;while (path ! = null) {if (Path.equalsignorecase (path1)) return true;if (Path.equals (globalconsts.root_path)) Break;path = new File ( Path). GetParent ();} return false;} When adding 2 paths, do you need to add the file delimiter public static string Makepath (String path1, String path2) {if (Path1.endswith (File.separator)) Return PATh1 + Path2;return path1 + file.separator + path2;} Get the storage directory for the SD card public static String Getsddirectory () {return environment.getexternalstoragedirectory (). GetPath (); Determine whether 1 files are "normal files", the files under Android_secure are not normal public static Boolean isnormalfile (String fullName) {return! Fullname.equals (android_secure);} According to the file path, the Java file is obtained and then packaged into fileinfopublic static FileInfo GetFileInfo (String filePath) {File Lfile = new file (FilePath); if (!lfile.exists ()) return null; FileInfo lfileinfo = new FileInfo (); lfileinfo.canread = Lfile.canread (); lfileinfo.canwrite = Lfile.canwrite (); Lfileinfo.ishidden = Lfile.ishidden (); lfileinfo.filename = Util.getnamefromfilepath (FilePath); Lfileinfo.modifieddate = Lfile.lastmodified (); lfileinfo.isdir = Lfile.isdirectory (); lfileinfo.filepath = FilePath; Lfileinfo.filesize = Lfile.length (); return lfileinfo;} Depending on the file object, and the options such as FilenameFilter, the fileinfo//of the wrapper needs to be noted, and if file is a directory, count is the number of files in the current directory. If it is a normal file, the file size is calculated. This time, we know the meaning of the Count field is public static FileInfo GetFileInfo (File F, FilenameFilter FIlter,boolean ShowHidden) {FileInfo lfileinfo = new FileInfo (); String FilePath = F.getpath (); File Lfile = new file (filePath); lfileinfo.canread = Lfile.canread (); lfileinfo.canwrite = Lfile.canwrite (); Lfileinfo.ishidden = Lfile.ishidden (); lfileinfo.filename = F.getname (); lfileinfo.modifieddate = LFile.lastModified () ; lfileinfo.isdir = Lfile.isdirectory (); Lfileinfo.filepath = Filepath;if (lfileinfo.isdir) {int lCount = 0; file[] Files = lfile.listfiles (filter);//NULL means we cannot access this dirif (files = null) {return null;} for (File child:files) {if ((!child.ishidden () | | showhidden) && util.isnormalfile (Child.getabsolutepath ())) { lcount++;}} Lfileinfo.count = LCount;} else {lfileinfo.filesize = Lfile.length ();} return lfileinfo;} /* * A new way to get the apk icon, the previous failure is due to a bug in Android, through Appinfo.publicsourcedir = * Apkpath, to fix this problem, see: */HTTP code.google.com/p/android/issues/detail?id=9151 */public Static drawable Getapkicon (context context, String Apkpath) { The Android system provides us with many service management classes,Includes Activitymanager, PowerManager (Power Management), Audiomanager (audio management). Packagemanager is primarily a management application package, through which you can obtain application information Packagemanager PM = Context.getpackagemanager (); PackageInfo info = pm.getpackagearchiveinfo (apkpath,packagemanager.get_activities); if (info! = null) {ApplicationInfo AppInfo = Info.applicationinfo;appinfo.sourcedir = Apkpath;appinfo.publicsourcedir = apkpath;try {return Appinfo.loadicon (PM);} catch (OutOfMemoryError e) {log.e (Log_tag, e.tostring ());}} return null;} Gets the file extension public static string Getextfromfilename (string filename) {int dotposition = Filename.lastindexof ('. '); if (dotposition! =-1) {return filename.substring (dotposition + 1, filename.length ());} Return "";} Get the file name minus "file suffix", such as "c:/a/b/c.png", Output "c:/a/b/c" public static string Getnamefromfilename (string filename) {int Dotposition = Filename.lastindexof ('. '); if (dotposition! =-1) {return filename.substring (0, dotposition);}    Return "";} From the file path, get the path public static string Getpathfromfilepath (string filepath) {int pos = Filepath.lastIndexOf ('/'); if (pos! =-1) {return filepath.substring (0, POS);} Return "";} From the file path, get the file name (with a suffix, if any) public static string Getnamefromfilepath (string filepath) {int pos = Filepath.lastindexof ('/'); if (pos! =-1) {return filepath.substring (pos + 1);} Return "";} return new file path if successful, or return nullpublic static string CopyFile (String src, string dest) {File File = N EW File (SRC); if (!file.exists () | | | file.isdirectory ()) {LOG.V (Log_tag, "copyfile:file not exist or is directory," + src) ; return null;} FileInputStream fi = null; FileOutputStream fo = null;try {fi = new FileInputStream (file); File Destplace = new file (dest), if (!destplace.exists ()) {if (!destplace.mkdirs ()) return null;} String destpath = Util.makepath (dest, File.getname ()); File DestFile = new file (destpath); int i = 1;while (Destfile.exists ()) {String destname = Util.getnamefromfilename (file.ge Tname ()) + "" + i++ + "." + Util.getextfromfilename (File.getname ());d Estpath = Util.makepath (dest, destname);d estfile = new FilE (destpath);} if (!destfile.createnewfile ()) return NULL;FO = new FileOutputStream (destfile); int count = 102400;byte[] buffer = new byte[ Count];int read = 0;while ((read = fi.read (buffer, 0, count))! =-1) {fo.write (buffer, 0, read);} Todo:set access Privilegereturn DestPath;} catch (FileNotFoundException e) {log.e (Log_tag, "Copyfile:file not found," + src); E.printstacktrace ();} catch (IOException e) {log.e (Log_tag, "copyFile:" + e.tostring ());} Finally {try {if (fi! = null) fi.close (); if (fo! = null) Fo.close ();} catch (IOException e) {e.printstacktrace ()}} return null;} Does not include SD card folderprivate static string[] Sysfiledirs = new string[] {"Miren_browser/imagecaches"};//judge a Files need to be displayed, depending on the settings in the setting. Special Note: A System file directory is not displayed. public static Boolean Shouldshowfile (String path) {return shouldshowfile (new File);} Determine if a file needs to be displayed, based on the settings in setting. Special Note: A System file directory is not displayed. public static Boolean shouldshowfile (file file) {Boolean show = Settings.instance (). Getshowdotandhiddenfiles (); if (showReturn True;if (File.ishidden ()) Return false;if (File.getname (). StartsWith (".")) return false; String sdfolder = Getsddirectory (); for (String s:sysfiledirs) {if (File.getpath (). StartsWith (Makepath (Sdfolder, s))) return false;} return true;} Gets the default collection of collection public static arraylist<favoriteitem> Getdefaultfavorites (context context) according to contextual object contexts { arraylist<favoriteitem> list = new arraylist<favoriteitem> (); List.add (New Favoriteitem ( Context.getstring (R.string.favorite_photo), Makepath (Getsddirectory (), "Dcim/camera")); List.add (New FavoriteItem (Context.getstring (R.string.favorite_sdcard), Getsddirectory ())); /List.add (New Favoriteitem (Context.getstring (R.string.favorite_root),//Getsddirectory ()); List.add (new Favoriteitem (Context.getstring (R.string.favorite_screen_cap), Makepath (Getsddirectory (), "MIUI/screen_cap")); List.add (New Favoriteitem (Context.getstring (R.string.favorite_ringtone), Makepath (Getsddirectory (), "MIUI/ Ringtone ")); return list;} To set the text public to a textview in a viewStatic Boolean SetText (view view, int ID, String text) {TextView TextView = (TextView) View.findviewbyid (ID); if (TextView = = null) return False;textview.settext (text); return true;} Sets the text public static Boolean setText (view view, int id, int text) {TextView TextView = (TextView) View.fin to a TextView in view Dviewbyid (ID); if (TextView = = null) return False;textview.settext (text); return true;} Comma separated numberpublic static String Convertnumber (long number) {return String.Format ("%,d", number);} Storage, G M K bpublic static String convertstorage (long size) {long kb = 1024;long MB = KB * 1024;long GB = MB * 1024;  if (size >= GB) {return String.Format ("%.1f GB", (float) size/gb);} else if (size >= MB) {float F = (float) Size/ Mb;return String.Format (F > 100?) "%.0f MB": "%.1f MB", f);} else if (size >= kb) {float F = (float) Size/kb;return String.Format (F > 100?) "%.0f KB": "%.1f KB", f);} Elsereturn String.Format ("%d B", size);} public static class Sdcardinfo {publicLong total;public long Free;} Obtain various information about SD card, total capacity size and remaining capacity size, etc. public static Sdcardinfo Getsdcardinfo () {String sdcstring = Android.os.Environment.getExternalStorageState (); if (Sdcstring.equals (Android.os.Environment.MEDIA_MOUNTED)) { File pathfile = Android.os.Environment.getExternalStorageDirectory (); try {android.os.StatFs StatFs = new Android.os.StatFs (Pathfile.getpath ());//Gets the total number of blocks on the sdcard long ntotalblocks = Statfs.getblockcount ();// Get Sizelong nblocsize = Statfs.getblocksize () for each block on sdcard,//Get the number of blocks that can be used by the program long Navailablock = Statfs.getavailableblocks ();//Gets the number of all remaining blocks (including chunks that are not available in the General program reserved) long Nfreeblock = Statfs.getfreeblocks ();  Sdcardinfo info = new Sdcardinfo ();//Calculate sdcard Total capacity Size Mbinfo.total = ntotalblocks * nblocsize;//calculate sdcard remaining Size Mbinfo.free = Navailablock * Nblocsize;return info;} catch (IllegalArgumentException e) {log.e (Log_tag, e.tostring ());}} return null;} Displays a system notification public static void Shownotification (context context, Intent intent,string title, String body, int drawableid){Notificationmanager manager = (Notificationmanager) context.getsystemservice (Context.notification_service); Notification Notification = new Notification (Drawableid, Body,system.currenttimemillis ()); notification.flags = Notification.flag_auto_cancel;notification.defaults = notification.default_sound;if (Intent = = NULL) {//FIXEME: Category tab is Disabledintent = new Intent (context, fileviewactivity.class);} Pendingintent contentintent = pendingintent.getactivity (Context, 0,intent, pendingintent.flag_one_shot); Notification.setlatesteventinfo (context, title, body, contentintent); Manager.notify (drawableid, notification);} Format the millisecond format time public static String formatdatestring (context context, long times) {DateFormat DateFormat = Android.text.format.DateFormat.getDateFormat (context);D Ateformat TimeFormat = Android.text.format.DateFormat.getTimeFormat (context);D ate date = new Date (time), return Dateformat.format (Date) + "" + Timeformat.format (date);} public static void Updateactionmodetitle (ActionmoDe mode, Context context,int selectednum) {if (mode! = null) {Mode.settitle (context.getstring (r.string.multi_select_ Title,selectednum)); if (Selectednum = = 0) {mode.finish ();}}} Mimetypepublic static hashset<string> Sdocmimetypesset = new Hashset<string> () {{Add ("Text/plain"); Add ( "Text/plain"), Add ("Application/pdf"), Add ("Application/msword"), Add ("application/vnd.ms-excel"), Add (" Application/vnd.ms-excel ");}; public static String Szipfilemimetype = "Application/zip";p ublic static int category_tab_index = 0;public static int Sdcar D_tab_index = 1;}






Encountered a strange problem, in order to verify a function, wrote a main function to execute, the result has been a wonderful matter ~


Execute the following code in the Java environment of the project, normal output.
public class Test {public static void main (string[] args) {System.out.println (Getnamefromfilename ("c:/a/b/c.png"));} public static string Getnamefromfilename (string filename) {int dotposition = Filename.lastindexof ('. '); if (dotposition! =-1) {return filename.substring (0, dotposition);} Return "";}}


Print "C:/A/B/C"


In the Android environment of the project, actually directly to the JVM crashed, unknown so ah ~
Invalid layout of java.lang.String at value
#
# A Fatal error has been detected by the Java Runtime environment:
#
# Internal Error (javaclasses.cpp:129), pid=8236, tid=3188
# fatal Error:invalid layout of preloaded class
#
# JRE VERSION:7.0_17-B02
# Java Vm:java HotSpot (TM) 64-bit Server VM (23.7-b01 mixed mode windows-amd64 compressed oops)
# Failed to write core dump. Minidumps is not enabled by default on client versions of Windows
#
# A error report file with more information is saved as:
# J:\AndroidCenter\MiCodeFileExplorer\hs_err_pid8236.log
#
# If you would as to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
#

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Xiaomi Open source File Manager micodefileexplorer-Source Research (3)-most used tool class Util

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.