Java tutorial
/* * Copyright (C) 2012 www.amsoft.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sogrey.frame.utils; import android.annotation.SuppressLint; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.provider.ContactsContract; import android.text.TextUtils; import android.util.Base64; import org.sogrey.frame.global.AppConfig; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; //import org.apache.http.Header; //import org.apache.http.HttpResponse; /** * 2012 amsoft.cn ??AbFileUtil.java ???. * * @author * @version v1.0 * @date2013-01-18 ?11:52:13 */ @SuppressLint("DefaultLocale") public class FileUtil { public static final int SIZETYPE_B = 1;// ????Bdouble public static final int SIZETYPE_KB = 2;// ????KBdouble public static final int SIZETYPE_MB = 3;// ????MBdouble public static final int SIZETYPE_GB = 4;// ????GBdouble private static final String TAG = "AbFileUtil"; /** APP. */ private static String downloadRootDir = null; /** . */ private static String imageDownloadDir = null; /** . */ private static String fileDownloadDir = null; /** . */ private static String cacheDownloadDir = null; /** ?. */ private static String dbDownloadDir = null; /** . */ private static String logDir = null; /** 200M?SD. */ private static int freeSdSpaceNeededToCache = 200 * 1024 * 1024; /** * ???SD??SD?. * * @param url * ? * @param type * ???AbImageUtil ?? * @param desiredWidth * * @param desiredHeight * * * @return Bitmap */ public static Bitmap getBitmapFromSD(String url, int type, int desiredWidth, int desiredHeight) { Bitmap bitmap = null; try { if (StrUtil.isEmpty(url)) { return null; } // SD?? ??SD? if (!isCanUseSD() || freeSdSpaceNeededToCache < freeSpaceOnSD()) { bitmap = getBitmapFromURL(url, type, desiredWidth, desiredHeight); return bitmap; } // ?? String downFilePath = downloadFile(url, imageDownloadDir); if (downFilePath != null) { // ? return getBitmapFromSD(new File(downFilePath), type, desiredWidth, desiredHeight); } else { return null; } } catch (Exception e) { e.printStackTrace(); } return bitmap; } /** * ???SD??. * * @param file * the file * @param type * ???AbConstant ?? * @param desiredWidth * * @param desiredHeight * * * @return Bitmap */ public static Bitmap getBitmapFromSD(File file, int type, int desiredWidth, int desiredHeight) { Bitmap bitmap = null; try { // SD?? if (!isCanUseSD()) { return null; } // ? if (!file.exists()) { return null; } // if (type == AbImageUtil.CUTIMG) { bitmap = AbImageUtil.cutImg(file, desiredWidth, desiredHeight); } else if (type == AbImageUtil.SCALEIMG) { bitmap = AbImageUtil.scaleImg(file, desiredWidth, desiredHeight); } else { bitmap = AbImageUtil.getBitmap(file); } } catch (Exception e) { e.printStackTrace(); } return bitmap; } /** * ???SD??. * * @param file * the file * * @return Bitmap */ public static Bitmap getBitmapFromSD(File file) { Bitmap bitmap = null; try { // SD?? if (!isCanUseSD()) { return null; } // ? if (!file.exists()) { return null; } // bitmap = AbImageUtil.getBitmap(file); } catch (Exception e) { e.printStackTrace(); } return bitmap; } /** * ??byte[]. * * @param imgByte * byte[] * @param fileName * ?????.jpg * @param type * ???AbConstant * @param desiredWidth * * @param desiredHeight * * * @return Bitmap */ public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth, int desiredHeight) { FileOutputStream fos = null; DataInputStream dis = null; ByteArrayInputStream bis = null; Bitmap bitmap = null; File file = null; try { if (imgByte != null) { file = new File(imageDownloadDir + fileName); if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); int readLength = 0; bis = new ByteArrayInputStream(imgByte); dis = new DataInputStream(bis); byte[] buffer = new byte[1024]; while ((readLength = dis.read(buffer)) != -1) { fos.write(buffer, 0, readLength); try { Thread.sleep(500); } catch (Exception e) { } } fos.flush(); bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight); } } catch (Exception e) { e.printStackTrace(); } finally { if (dis != null) { try { dis.close(); } catch (Exception e) { } } if (bis != null) { try { bis.close(); } catch (Exception e) { } } if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return bitmap; } /** * ???URL?. * * @param url * ?? * @param type * ???AbConstant * @param desiredWidth * * @param desiredHeight * * * @return Bitmap */ public static Bitmap getBitmapFromURL(String url, int type, int desiredWidth, int desiredHeight) { Bitmap bit = null; try { bit = AbImageUtil.getBitmap(url, type, desiredWidth, desiredHeight); } catch (Exception e) { LogUtil.d(FileUtil.class, "" + e.getMessage()); } return bit; } /** * ???src?. * * @param src * srcimage/arrow.png? * * @return Bitmap */ public static Bitmap getBitmapFromSrc(String src) { Bitmap bit = null; try { bit = BitmapFactory.decodeStream(FileUtil.class.getResourceAsStream(src)); } catch (Exception e) { LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return bit; } /** * ???Asset?. * * @param context * the context * @param fileName * the file name * * @return Bitmap */ public static Bitmap getBitmapFromAsset(Context context, String fileName) { Bitmap bit = null; try { AssetManager assetManager = context.getAssets(); InputStream is = assetManager.open(fileName); bit = BitmapFactory.decodeStream(is); } catch (Exception e) { LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return bit; } /** * ???Asset?. * * @param context * the context * @param fileName * the file name * * @return Drawable */ public static Drawable getDrawableFromAsset(Context context, String fileName) { Drawable drawable = null; try { AssetManager assetManager = context.getAssets(); InputStream is = assetManager.open(fileName); drawable = Drawable.createFromStream(is, null); } catch (Exception e) { LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return drawable; } /** * ???xx.??. * * @param response * the response * @return ?? */ // public static String getRealFileName(HttpResponse response) { // String name = null; // try { // if (response == null) { // return name; // } // // ??? // Header[] headers = response.getHeaders("content-disposition"); // for (int i = 0; i < headers.length; i++) { // Matcher m = Pattern.compile(".*filename=(.*)").matcher( // headers[i].getValue()); // if (m.find()) { // name = m.group(1).replace("\"", ""); // } // } // } catch (Exception e) { // e.printStackTrace(); // LogUtil.e(FileUtil.class, "???"); // } // return name; // } /** * SD?.SD????? * * @param url * ?? * @param dirPath * the dir path * * @return ? */ public static String downloadFile(String url, String dirPath) { InputStream in = null; FileOutputStream fileOutputStream = null; HttpURLConnection connection = null; String downFilePath = null; File file = null; try { if (!isCanUseSD()) { return null; } // SD??? String fileNameNoMIME = getCacheFileNameFromUrl(url); File parentFile = new File(dirPath); File[] files = parentFile.listFiles(); for (int i = 0; i < files.length; ++i) { String fileName = files[i].getName(); String name = fileName.substring(0, fileName.lastIndexOf(".")); if (name.equals(fileNameNoMIME)) { // return files[i].getPath(); } } URL mUrl = new URL(url); connection = (HttpURLConnection) mUrl.openConnection(); connection.connect(); // ??? String fileName = getCacheFileNameFromUrl(url, connection); file = new File(imageDownloadDir, fileName); downFilePath = file.getPath(); if (!file.exists()) { file.createNewFile(); } else { // return file.getPath(); } in = connection.getInputStream(); fileOutputStream = new FileOutputStream(file); byte[] b = new byte[1024]; int temp = 0; while ((temp = in.read(b)) != -1) { fileOutputStream.write(b, 0, temp); } } catch (Exception e) { e.printStackTrace(); LogUtil.e(FileUtil.class, ","); // ?,0B??? if (file != null) { file.delete(); } file = null; downFilePath = null; } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (connection != null) { connection.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } return downFilePath; } /** * ????. * * @param Url * * * @return int ? */ public static int getContentLengthFromUrl(String Url) { int mContentLength = 0; try { URL url = new URL(Url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, " + "application/x-shockwave-flash, application/xaml+xml, " + "application/vnd.ms-xpsdocument, application/x-ms-xbap, " + "application/x-ms-application, application/vnd.ms-excel, " + "application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", Url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET" + " CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR" + " 3.0.4506.2152; .NET CLR 3.5.30729)"); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { // ???? mContentLength = mHttpURLConnection.getContentLength(); } } catch (Exception e) { e.printStackTrace(); LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return mContentLength; } /** * ???.???. * * @param url * ? * @param response * the response * @return ?? */ // public static String getCacheFileNameFromUrl(String url, // HttpResponse response) { // if (StrUtil.isEmpty(url)) { // return null; // } // String name = null; // try { // // ?? // String suffix = getMIMEFromUrl(url, response); // if (StrUtil.isEmpty(suffix)) { // suffix = ".ab"; // } // name = MD5.md5(url) + suffix; // } catch (Exception e) { // e.printStackTrace(); // } // return name; // } /** * ????. * * @param url * ? * * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (StrUtil.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, " + "application/x-shockwave-flash, application/xaml+xml, " + "application/vnd.ms-xpsdocument, application/x-ms-xbap, " + "application/x-ms-application, application/vnd.ms-excel, " + "application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); LogUtil.e(FileUtil.class, "???"); } return name; } /** * ???xx.??. * * @param connection * * * @return ?? */ public static String getRealFileName(HttpURLConnection connection) { String name = null; try { if (connection == null) { return name; } if (connection.getResponseCode() == 200) { for (int i = 0;; i++) { String mime = connection.getHeaderField(i); if (mime == null) { break; } // "Content-Disposition","attachment; filename=1.txt" // Content-Length if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase()); if (m.find()) { return m.group(1).replace("\"", ""); } } } } } catch (Exception e) { e.printStackTrace(); LogUtil.e(FileUtil.class, "???"); } return name; } /** * ??. * * @param url * ? * @param response * the response * @return ? */ // public static String getMIMEFromUrl(String url, HttpResponse response) { // // if (StrUtil.isEmpty(url)) { // return null; // } // String mime = null; // try { // // ?? // if (url.lastIndexOf(".") != -1) { // mime = url.substring(url.lastIndexOf(".")); // if (mime.indexOf("/") != -1 || mime.indexOf("?") != -1 // || mime.indexOf("&") != -1) { // mime = null; // } // } // if (StrUtil.isEmpty(mime)) { // // ??? ? // String fileName = getRealFileName(response); // if (fileName != null && fileName.lastIndexOf(".") != -1) { // mime = fileName.substring(fileName.lastIndexOf(".")); // } // } // } catch (Exception e) { // e.printStackTrace(); // } // return mime; // } /** * ????????/?? * * @param path * * * @return * * @author Sogrey * @date 2015630 */ public static String getFileName(String path) { return new File(path.trim()).getName(); } /** * ??????. * * @param url * ? * * @return ?? */ public static String getCacheFileNameFromUrl(String url) { if (StrUtil.isEmpty(url)) { return null; } String name = null; try { name = MD5.md5(url); } catch (Exception e) { e.printStackTrace(); } return name; } /** * ???.???. * * @param url * ? * @param connection * the connection * * @return ?? */ public static String getCacheFileNameFromUrl(String url, HttpURLConnection connection) { if (StrUtil.isEmpty(url)) { return null; } String name = null; try { // ?? String suffix = getMIMEFromUrl(url, connection); if (StrUtil.isEmpty(suffix)) { suffix = ".ab"; } name = MD5.md5(url) + suffix; } catch (Exception e) { e.printStackTrace(); } return name; } /** * ??. * * @param url * ? * @param connection * the connection * * @return ? */ public static String getMIMEFromUrl(String url, HttpURLConnection connection) { if (StrUtil.isEmpty(url)) { return null; } String suffix = null; try { // ?? if (url.lastIndexOf(".") != -1) { suffix = url.substring(url.lastIndexOf(".")); if (suffix.indexOf("/") != -1 || suffix.indexOf("?") != -1 || suffix.indexOf("&") != -1) { suffix = null; } } if (StrUtil.isEmpty(suffix)) { // ??? ? String fileName = getRealFileName(connection); if (fileName != null && fileName.lastIndexOf(".") != -1) { suffix = fileName.substring(fileName.lastIndexOf(".")); } } } catch (Exception e) { e.printStackTrace(); } return suffix; } /** * ??sd??byte[]. * * @param path * sd? * * @return byte[] */ public static byte[] getByteArrayFromSD(String path) { byte[] bytes = null; ByteArrayOutputStream out = null; try { File file = new File(path); // SD?? if (!isCanUseSD()) { return null; } // ? if (!file.exists()) { return null; } long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { return null; } FileInputStream in = new FileInputStream(path); out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int size = 0; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); bytes = out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { } } } return bytes; } /** * ??byte. * * @param path * the path * @param content * the content * @param create * the create */ public static void writeByteArrayToSD(String path, byte[] content, boolean create) { FileOutputStream fos = null; try { File file = new File(path); // SD?? if (!isCanUseSD()) { return; } // ? if (!file.exists()) { if (create) { File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); file.createNewFile(); } } else { return; } } fos = new FileOutputStream(path); fos.write(content); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { } } } } /** * ??SD??. * * @return true ?,false?? */ public static boolean isCanUseSD() { try { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); } catch (Exception e) { e.printStackTrace(); } return false; } /** * ???. * * @param context * the context */ public static void initFileDir(Context context) { PackageInfo info = AppUtil.getPackageInfo(context); // . String downloadRootPath = File.separator + AppConfig.DOWNLOAD_ROOT_DIR + File.separator + info.packageName + File.separator; // . String imageDownloadPath = downloadRootPath + AppConfig.DOWNLOAD_IMAGE_DIR + File.separator; // . String fileDownloadPath = downloadRootPath + AppConfig.DOWNLOAD_FILE_DIR + File.separator; // . String cacheDownloadPath = downloadRootPath + AppConfig.CACHE_DIR + File.separator; // DB. String dbDownloadPath = downloadRootPath + AppConfig.DB_DIR + File.separator; // . String logPath = downloadRootPath + AppConfig.LOG_DIR + File.separator; try { if (!isCanUseSD()) { downloadRootDir = context.getFilesDir().getPath(); cacheDownloadDir = context.getCacheDir().getPath(); imageDownloadDir = downloadRootDir; fileDownloadDir = downloadRootDir; dbDownloadDir = downloadRootDir; logDir = downloadRootDir; return; } else { File root = Environment.getExternalStorageDirectory(); File downloadDir = new File(root.getAbsolutePath() + downloadRootPath); if (!downloadDir.exists()) { downloadDir.mkdirs(); } downloadRootDir = downloadDir.getPath(); File cacheDownloadDirFile = new File(root.getAbsolutePath() + cacheDownloadPath); if (!cacheDownloadDirFile.exists()) { cacheDownloadDirFile.mkdirs(); } cacheDownloadDir = cacheDownloadDirFile.getPath(); File imageDownloadDirFile = new File(root.getAbsolutePath() + imageDownloadPath); if (!imageDownloadDirFile.exists()) { imageDownloadDirFile.mkdirs(); } imageDownloadDir = imageDownloadDirFile.getPath(); File fileDownloadDirFile = new File(root.getAbsolutePath() + fileDownloadPath); if (!fileDownloadDirFile.exists()) { fileDownloadDirFile.mkdirs(); } fileDownloadDir = fileDownloadDirFile.getPath(); File dbDownloadDirFile = new File(root.getAbsolutePath() + dbDownloadPath); if (!dbDownloadDirFile.exists()) { dbDownloadDirFile.mkdirs(); } dbDownloadDir = dbDownloadDirFile.getPath(); File logDirFile = new File(root.getAbsolutePath() + logPath); if (!logDirFile.exists()) { logDirFile.mkdirs(); } logDir = logDirFile.getPath(); } } catch (Exception e) { e.printStackTrace(); } } /** * sdcard. * * @return the int */ @SuppressWarnings("deprecation") public static int freeSpaceOnSD() { StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat.getBlockSize()) / 1024 * 1024; return (int) sdFreeMB; } /** * . * * @return true, if successful */ public static boolean clearDownloadFile() { try { if (!isCanUseSD()) { return false; } File path = Environment.getExternalStorageDirectory(); File fileDirectory = new File(path.getAbsolutePath() + downloadRootDir); File[] files = fileDirectory.listFiles(); if (files == null) { return true; } for (int i = 0; i < files.length; i++) { files[i].delete(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * ???Assets. * * @param context * the context * @param name * the name * @param encoding * the encoding * * @return the string */ public static String readAssetsByName(Context context, String name, String encoding) { String text = null; InputStreamReader inputReader = null; BufferedReader bufReader = null; try { inputReader = new InputStreamReader(context.getAssets().open(name)); bufReader = new BufferedReader(inputReader); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = bufReader.readLine()) != null) { buffer.append(line); } text = new String(buffer.toString().getBytes(), encoding); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bufReader != null) { bufReader.close(); } if (inputReader != null) { inputReader.close(); } } catch (Exception e) { e.printStackTrace(); } } return text; } /** * ???Raw. * * @param context * the context * @param id * the id * @param encoding * the encoding * * @return the string */ public static String readRawByName(Context context, int id, String encoding) { String text = null; InputStreamReader inputReader = null; BufferedReader bufReader = null; try { inputReader = new InputStreamReader(context.getResources().openRawResource(id)); bufReader = new BufferedReader(inputReader); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = bufReader.readLine()) != null) { buffer.append(line); } text = new String(buffer.toString().getBytes(), encoding); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bufReader != null) { bufReader.close(); } if (inputReader != null) { inputReader.close(); } } catch (Exception e) { e.printStackTrace(); } } return text; } /** * Gets the download root dir. * * @param context * the context * * @return the download root dir */ public static String getDownloadRootDir(Context context) { if (downloadRootDir == null) { initFileDir(context); } return downloadRootDir; } /** * Gets the image download dir. * * @param context * the context * * @return the image download dir */ public static String getImageDownloadDir(Context context) { if (downloadRootDir == null) { initFileDir(context); } return imageDownloadDir; } /** * Gets the file download dir. * * @param context * the context * * @return the file download dir */ public static String getFileDownloadDir(Context context) { if (downloadRootDir == null) { initFileDir(context); } return fileDownloadDir; } /** * Gets the cache download dir. * * @param context * the context * * @return the cache download dir */ public static String getCacheDownloadDir(Context context) { if (downloadRootDir == null) { initFileDir(context); } return cacheDownloadDir; } /** * Gets the db download dir. * * @param context * the context * * @return the db download dir */ public static String getDbDownloadDir(Context context) { if (downloadRootDir == null) { initFileDir(context); } return dbDownloadDir; } /** * Gets the log dir. * * @param context * the context * * @return the log dir */ public static String getLogDir(Context context) { if (logDir == null) { initFileDir(context); } return logDir; } /** * Gets the free sd space needed to cache. * * @return the free sd space needed to cache */ public static int getFreeSdSpaceNeededToCache() { return freeSdSpaceNeededToCache; } /** * ? * * @param file */ public static boolean createDipPath(String file) { String parentFile = file.substring(0, file.lastIndexOf("/")); File file1 = new File(file); File parent = new File(parentFile); if (!parent.exists()) { parent.mkdirs(); } boolean isCreated = false; if (!file1.exists()) { try { isCreated = file1.createNewFile(); LogUtil.i(TAG, "Create new file :" + file); } catch (IOException e) { LogUtil.e(TAG, e.getMessage()); } } return isCreated; } /** * * * @param path */ public static boolean deleteFile(String path) { boolean bl; File file = new File(path); if (file.exists()) { bl = file.delete(); } else { bl = false; } return bl; } /** * bitmap? * * @param bitmap * @param imagePath */ @SuppressLint("NewApi") public static String saveBitmap(Bitmap bitmap, String imagePath, int s) { File file = new File(imagePath); if (createDipPath(imagePath)) return null; FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); if (imagePath.toLowerCase().endsWith(".png")) { bitmap.compress(Bitmap.CompressFormat.PNG, s, fOut); } else if (imagePath.toLowerCase().endsWith(".jpg") || imagePath.toLowerCase().endsWith(".jpeg")) { bitmap.compress(Bitmap.CompressFormat.JPEG, s, fOut); } else { bitmap.compress(Bitmap.CompressFormat.WEBP, s, fOut); } } catch (FileNotFoundException e) { e.printStackTrace(); return null; } finally { try { if (fOut != null) { fOut.flush(); } } catch (IOException e) { e.printStackTrace(); } try { if (fOut != null) { fOut.close(); } } catch (IOException e) { e.printStackTrace(); } } return imagePath; } /** * ? * * @param sourcePath * @param toPath * * @author Sogrey * @date 2015630 */ public static void copyFile(String sourcePath, String toPath) { File sourceFile = new File(sourcePath); File targetFile = new File(toPath); createDipPath(toPath); try { BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { // ? inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); // ? outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); // byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // ? outBuff.flush(); } finally { // ? if (inBuff != null) inBuff.close(); if (outBuff != null) outBuff.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * ? * * @param sourceFile * @param targetFile * * @author Sogrey * @date 2015630 */ public static void copyFile(File sourceFile, File targetFile) { try { BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { // ? inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); // ? outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); // byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // ? outBuff.flush(); } finally { // ? if (inBuff != null) inBuff.close(); if (outBuff != null) outBuff.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * ?Base64 * * @param path * * @return * * @author Sogrey * @date 2015723 */ public static String getBase64FromPath(String path) { String base64 = ""; try { File file = new File(path); byte[] buffer = new byte[(int) file.length() + 100]; @SuppressWarnings("resource") int length = new FileInputStream(file).read(buffer); base64 = Base64.encodeToString(buffer, 0, length, Base64.DEFAULT); } catch (IOException e) { e.printStackTrace(); } return base64; } /** * ???? * * @param filePath * * @param sizeType * ??1B{@link #SIZETYPE_B}?2KB * {@link #SIZETYPE_KB}?3MB{@link #SIZETYPE_MB} * ?4GB{@link #SIZETYPE_GB} * * @return double? */ public static double getFileOrFilesSize(String filePath, int sizeType) { File file = new File(filePath); long blockSize = 0; try { if (file.isDirectory()) { blockSize = getFileSizes(file); } else { blockSize = getFileSize(file); } } catch (Exception e) { e.printStackTrace(); LogUtil.e("??", filePath + ">>>?!"); } return FormetFileSize(blockSize, sizeType); } /** * ? * * @param filePath * * * @return B?KB?MB?GB */ public static String getAutoFileOrFilesSize(String filePath) { File file = new File(filePath); long blockSize = 0; try { if (file.isDirectory()) { blockSize = getFileSizes(file); } else { blockSize = getFileSize(file); } } catch (Exception e) { e.printStackTrace(); LogUtil.e("??", "?!"); } return FormetFileSize(blockSize); } /** * ?? * * @param file * * @return * * @throws Exception */ private static long getFileSize(File file) throws Exception { long size = 0; if (file.exists()) { FileInputStream fis = null; fis = new FileInputStream(file); size = fis.available(); } else { file.createNewFile(); LogUtil.e("??", "?!"); } return size; } /** * ? * * @param f * * @return * * @throws Exception */ private static long getFileSizes(File f) throws Exception { long size = 0; File flist[] = f.listFiles(); for (int i = 0; i < flist.length; i++) { if (flist[i].isDirectory()) { size = size + getFileSizes(flist[i]); } else { size = size + getFileSize(flist[i]); } } return size; } /** * ?? * * @param fileS * * @return */ public static String FormetFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; String wrongSize = "0B"; if (fileS == 0) { return wrongSize; } if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "KB"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "MB"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "GB"; } return fileSizeString; } /** * ??,? * * @param fileS * @param sizeType * * @return */ private static double FormetFileSize(long fileS, int sizeType) { DecimalFormat df = new DecimalFormat("#.00"); double fileSizeLong = 0; switch (sizeType) { case SIZETYPE_B: fileSizeLong = Double.valueOf(df.format((double) fileS)); break; case SIZETYPE_KB: fileSizeLong = Double.valueOf(df.format((double) fileS / 1024)); break; case SIZETYPE_MB: fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576)); break; case SIZETYPE_GB: fileSizeLong = Double.valueOf(df.format((double) fileS / 1073741824)); break; default: break; } return fileSizeLong; } /** * ? * * @param deleteThisPath * ? * @param filePath * * * @return */ public static void deleteFolderFile(String filePath, boolean deleteThisPath) { if (!TextUtils.isEmpty(filePath)) { try { File file = new File(filePath); if (file.isDirectory()) {// ? File files[] = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFolderFile(files[i].getAbsolutePath(), true); } } if (deleteThisPath) { if (!file.isDirectory()) {// file.delete(); } else {// if (file.listFiles().length == 0) {// file.delete(); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * app * * @param context * * @author Sogrey * @date 2015-11-27?1:56:55 */ public static void openFolder(Context context, String path) { // Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // Uri uri = Uri.parse(path); // intent.setDataAndType(uri, "text/csv"); // try { // context.startActivity(Intent.createChooser(intent, "Open folder")); // } catch (Exception e) { // } // File root = new File(path); // Uri uri = Uri.fromFile(root); // Intent intent = new Intent(); // intent.setAction(android.content.Intent.ACTION_VIEW); // intent.setData(uri); // context.startActivity(intent); // Intent intent = new Intent(); // String videoPath = path;// // File file = new File(videoPath); // Uri uri = Uri.fromFile(file); // intent.setData(uri); // intent.setAction(android.content.Intent.ACTION_VIEW);// "com.xxx.xxx" // ??? // try { // context.startActivity(intent); // } catch (ActivityNotFoundException e) { // e.printStackTrace(); // } // Intent i = new Intent(Intent.ACTION_GET_CONTENT); // // i.setAction(android.content.Intent.ACTION_VIEW); // File file = new File(path); // i.setDataAndType(Uri.fromFile(file), "file/*"); // try { // context.startActivity(i); // } catch (Exception e) { // } // Intent intent = new Intent(); // File file = new File(path); // intent.setAction(android.content.Intent.ACTION_VIEW); // // intent.setData(Uri.fromFile(file)); // intent.setDataAndType(Uri.fromFile(file), "file/*"); // try { // context.startActivity(intent); // } catch (Exception e) { // } Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // intent.setType("*/*"); intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); File file = new File(path); intent.setData(Uri.fromFile(file)); // intent.setDataAndType(Uri.fromFile(file), "*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { context.startActivity(intent); } catch (ActivityNotFoundException ex) { ToastUtil.showToast(context, "?"); } } /** * * * @param file * ? */ public void DeleteFile(File file) { if (!file.exists()) { return; } else { if (file.isFile()) { file.delete(); return; } if (file.isDirectory()) { File[] childFile = file.listFiles(); if (childFile == null || childFile.length == 0) { file.delete(); return; } for (File f : childFile) { DeleteFile(f); } file.delete(); } } } /** * * * @param path * ? */ public void DeleteFile(String path) { DeleteFile(new File(path)); } /** * ???. */ public static class FileLastModifSort implements Comparator<File> { /* * (non-Javadoc) * * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(File arg0, File arg1) { if (arg0.lastModified() > arg1.lastModified()) { return 1; } else if (arg0.lastModified() == arg1.lastModified()) { return 0; } else { return -1; } } } }