MrShi
6 天以前 3a154bdb0a5aaa2c0ac3eac95a6ba747068bd454
keyCabinet-android/app/src/main/java/com/doumee/keyCabinet/utils/update/FileUtil.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,298 @@
package com.doumee.keyCabinet.utils.update;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DecimalFormat;
/**
 * æ–‡ä»¶å·¥å…·ç±»
 *
 * @author spring sky
 *
 */
public class FileUtil {
   /**
    * èŽ·å–ç›®å½•åç§°
    *
    * @param url
    * @return FileName
    */
   public static String getFileName(String url) {
      int lastIndexStart = url.lastIndexOf("/");
      if (lastIndexStart != -1) {
         return url.substring(lastIndexStart + 1, url.length());
      } else {
         return new Timestamp(System.currentTimeMillis()).toString();
      }
   }
   /**
    * æ–‡ä»¶æ˜¯å¦å­˜åœ¨
    *
    * @param path
    * @return
    */
   public static boolean FileIsExist(String path) {
      File file = new File(path);
      return file.exists();
   }
   /**
    * åˆ¤æ–­SD卡是否存在
    *
    * @return boolean
    */
   public static boolean checkSDCard() {
      if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
         return true;
      } else {
         return false;
      }
   }
   /**
    * ä¿å­˜æ–‡ä»¶åˆ°æŒ‡å®šç›®å½•
    *
    * @param context
    * @return æ–‡ä»¶ä¿å­˜çš„目录
    */
   public static String setMkdir(Context context) {
      String filePath = null;
      if (checkSDCard()) {
         filePath = Environment.getExternalStorageDirectory()
               + File.separator + "com.ahrykj.Weddingg" + File.separator
               + "downloads";
      } else {
         filePath = context.getCacheDir().getAbsolutePath() + File.separator
               + "com.ahrykj.Weddingg" + File.separator + "downloads";
      }
      File file = new File(filePath);
      if (!file.exists()) {
         file.mkdirs();
         Log.e("file", "目录不存在   åˆ›å»ºç›®å½•    ");
      } else {
         Log.e("file", "目录存在");
      }
      return filePath;
   }
   public static String getFile(Context context){
      File sdDir = null;
      boolean sdCardExist = Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED);// åˆ¤æ–­sd卡是否存在
      if (sdCardExist) {
         if (Build.VERSION.SDK_INT>=29){
            //Android10之后
            sdDir = context.getExternalFilesDir(null);
         }else {
            sdDir = Environment.getExternalStorageDirectory();// èŽ·å–SD卡根目录
         }
      } else {
         sdDir = Environment.getRootDirectory();// èŽ·å–è·Ÿç›®å½•
      }
      return sdDir.toString();
   }
   /**
    * èŽ·å–è·¯å¾„
    *
    * @return
    * @throws IOException
    */
   public static String getPath(Context context, String url) {
      String path = null;
      try {
         path = FileUtil.getFile(context) + File.separator
               + "ticketmachine.apk";
      } catch (Exception e) {
         e.printStackTrace();
      }
      return path;
   }
   public static long getFileSize(File f) throws Exception// å–得文件夹大小
   {
      long size = 0;
      File flist[] = f.listFiles();
      if (flist != null) {
         for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
               size = size + getFileSize(flist[i]);
            } else {
               size = size + flist[i].length();
            }
         }
      }
      return size;
   }
   /**
    * èŽ·å–æ–‡ä»¶çš„å¤§å°
    *
    * @param fileS
    *            æ–‡ä»¶çš„大小
    * @return
    */
   public static String FormetFileSize(long fileS) {// è½¬æ¢æ–‡ä»¶å¤§å°
      DecimalFormat df = new DecimalFormat("0.0");// #.00
      String fileSizeString = "";
      if (fileS < 1024) {
         if (fileS < 70) {
            fileSizeString = "0B";
         } else {
            fileSizeString = df.format((double) fileS) + "B";
         }
      } else if (fileS < 1048576) {
         fileSizeString = df.format((double) fileS / 1024) + "K";
      } else if (fileS < 1073741824) {
         fileSizeString = df.format((double) fileS / 1048576) + "M";
      } else {
         fileSizeString = df.format((double) fileS / 1073741824) + "G";
      }
      return fileSizeString;
   }
   /**
    * åˆ é™¤è¯¥ç›®å½•下的指定文件
    *
    * @param filePath
    *            æ–‡ä»¶ç›®å½•
    * @param fileName
    *            æ–‡ä»¶å
    * @return
    */
   public static boolean deleteFile(String filePath, String fileName) {
      if (FileIsExist(filePath + fileName)) {
         File file = new File(filePath + fileName);
         return file.delete();
      }
      return true;
   }
   /**
    * åˆ é™¤è¯¥è·¯å¾„指定的文件
    *
    * @param path
    *            æ–‡ä»¶è·¯å¾„
    * @return
    */
   public static boolean deleteFile(String path) {
      if (FileIsExist(path)) {
         File file = new File(path);
         return file.delete();
      }
      return true;
   }
   /**
    * åˆ é™¤æ–¹æ³• è¿™é‡Œåªä¼šåˆ é™¤æŸä¸ªæ–‡ä»¶å¤¹ä¸‹çš„æ–‡ä»¶ï¼Œå¦‚果传入的directory是个文件,将不做处理
    *
    * @param file
    */
   public static void deleteFilesByDirectory(File file) {
      if (file.isFile()) {
         file.delete();
         return;
      }
      if (file.isDirectory()) {
         File[] childFiles = file.listFiles();
         if (childFiles == null || childFiles.length == 0) {
            file.delete();
            return;
         }
         for (int i = 0; i < childFiles.length; i++) {
            deleteFilesByDirectory(childFiles[i]);
         }
         file.delete();
      }
   }
   //将Bitmap转换成File
   public static File saveBitmapFile(Bitmap bitmap){
      File file=new File("/sdcard/face.jpg");//将要保存图片的路径
      try {
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
         bos.flush();
         bos.close();
      } catch (IOException e) {
         return null;
      }
      return file;
   }
   public static interface DownLoadCallBack{
      void sucess();
      void err(String e);
   }
   public static void downLoadFile(String filePath,String url,DownLoadCallBack callBack){
      try {
         URL u = new URL(url);
         HttpURLConnection conn = (HttpURLConnection) u.openConnection();
         conn.setConnectTimeout(10000);
         int responeCode = conn.getResponseCode();
         InputStream is;
         if (responeCode == 200) {
            is = conn.getInputStream();
         } else {
            //连接失败
            if(callBack!=null){
               callBack.err("下载地址错误");
            }
            return;
         }
         int fileSize = conn.getContentLength();
         if (fileSize < 1 || is == null) {
            //文件大小不对
            if(callBack!=null){
               callBack.err("文件大小不对");
            }
            return;
         } else {
            //下载
            if (FileUtil.deleteFile(filePath)) {// åˆ é™¤åŽŸæ¥çš„å®‰è£…æ–‡ä»¶å†ä¸‹è½½
               FileOutputStream fos = new FileOutputStream(filePath);
               byte[] bytes = new byte[1024];
               int len = -1;
               while ((len = is.read(bytes)) != -1) {
                  fos.write(bytes, 0, len);
                  fos.flush();
               }
               //下载完成
               if(callBack!=null){
                  callBack.sucess();
               }
               is.close();
               fos.close();
            }
         }
      } catch (Exception e) {
         //下载报错
         if(callBack!=null){
            callBack.err(e.getMessage());
         }
         e.printStackTrace();
      }
   }
}