FileUtil工具類



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;



import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;

public class FileUtil {
   private static final int MAX_FILE_NUM_PER_DIR = 500;
   private static final int MAX_DIR_NUM = 200;
   private static final String TAG = LogTag.TAG_UTIL;

   public static void delAutoChangeMusicList(List<AudioInfo> miList, String logTag) {
      if (miList == null || miList.size() == 0) {
         return;
      }
      try {
         int miSize = miList.size();
         for (int i = 0; i < miSize; i++) {
            AudioInfo mi = miList.get(i);
            String md5 = mi.getMd5();
            String path = mi.getFilePath();
            File file = new File(path);
            if (file.exists()) {
               file.delete();

            }
         }
      } catch (Exception ex) {
         if (MyLog.isDyeLevel()) {
            MyLog.log(logTag, MyLog.DYE_LOG_LEVEL, "del AutoChangeMusicList fail", ex);
         }
      }
   }

   public static StorageInfo getAvailableVolumeByNeedSpace(long needSpace) {
      StorageVolume[] volumeArray = getVolumeList();
      StorageInfo firstSecondSI = null;
      long MIN_SIZE = 200 * 1024 * 1024L;
      for (int i = 0; i < volumeArray.length; i++) {
         StorageVolume vol = volumeArray[i];
         if (vol.isPrimary()) {
            StatFs loopStatFs = new StatFs(vol.getPath());
            long restSpace = loopStatFs.getAvailableBytes() - needSpace;
            if (restSpace > MIN_SIZE) {
               StorageInfo si = new StorageInfo();
               si.setStorageFlag(StorageInfo.PRIMARY_STORAGE_VOLUME);
               si.setRootPath(vol.getPath());
               return si;
            }
         } else {
            if (firstSecondSI == null) {
               StatFs loopStatFs = new StatFs(vol.getPath());
               long restSpace = loopStatFs.getAvailableBytes() - needSpace;

               if (restSpace > MIN_SIZE) {
                  StorageInfo si = new StorageInfo();
                  si.setStorageFlag(vol.getPath());
                  si.setRootPath(vol.getPath());
                  firstSecondSI = si;
               }
            } else {
               // already find
            }
         }

      }
      return firstSecondSI;
   }

   public static String[] getAllMusicDir() {
      StorageVolume[] volumeArray = getVolumeList();
      ArrayList<String> musicDirList = new ArrayList<String>();
      for (int i = 0; i < volumeArray.length; i++) {
         StorageVolume vol = volumeArray[i];
         String musicDir = getRootMusicDirByRootPath(vol.getPath());
         File file = new File(musicDir);
         if (file.exists()) {
            musicDirList.add(file.getAbsolutePath());
         }
      }
      return musicDirList.toArray(new String[musicDirList.size()]);
   }

   public static String getHandDownloadMusicDir() {
      return Environment.getExternalStorageDirectory().getPath() + CenterConstants.DISK_HAND_MUSIC_PATH;
   }

   private static String getRootMusicDirByRootPath(String rootPath) {
      return rootPath + CenterConstants.DISK_ROOT_MUSIC_PATH;
   }

   public static String getCommonMusicDirByRootPath(String rootPath) {
      return rootPath + CenterConstants.DISK_COMMON_MUSIC_PATH;
   }

   public static String getChangeMusicDir(String rootPath, long userId) {
      return rootPath + CenterConstants.DISK_CHANGE_MUSIC_PATH + userId + "/";
   }

   public static String getChangeMusicPath(String rootPath, long userId, long listVer, ChangeMusicFileInfo cmfi) {
      String dir = rootPath + CenterConstants.DISK_CHANGE_MUSIC_PATH + userId + "/" + listVer + "/";
      String fileName = CenterMediaServer.genFileNameByMd5(dir, cmfi.getSongName(), cmfi.getMd5());
      String path = dir + fileName;
      return path;
   }

   public synchronized static String genMusicDir(Context ctx, String rootDirStr) {
      // SharedPreferences appSp =
      // ctx.getSharedPreferences(CenterPrefConstants.COMM_SP_NAME,
      // Context.MODE_PRIVATE);
      // String latestMusicDir =
      // appSp.getString(CenterPrefConstants.LATEST_MUSIC_DIR, "");
      // String retDirStr = null;
      // if(latestMusicDir == null || latestMusicDir.trim().length() == 0){
      // retDirStr = rootDir+"1/1/1/";
      // }else{
      // File someDir = new File(latestMusicDir);
      // File[] fileList = someDir.listFiles();
      // if(fileList == null || fileList.length<MAX_FILE_NUM_PER_DIR){
      // retDirStr = latestMusicDir;
      // }else{
      // String lastDirStr = latestMusicDir.substring(rootDir.length());
      // String[] lastDirs = lastDirStr.split("/",0);
      // String someDirStr = rootDir+lastDirs[0]+"/"+lastDirs[1];
      // someDir = new File(someDirStr);
      // fileList = someDir.listFiles();
      // if(fileList == null || fileList.length<MAX_DIR_NUM){
      // int thirdDirNum = Integer.parseInt(lastDirs[2]);
      // retDirStr =
      // rootDir+lastDirs[0]+"/"+lastDirs[1]+"/"+String.valueOf(thirdDirNum+1)+"/";
      //
      // }else{
      //
      // someDirStr = rootDir+lastDirs[0]+"/";
      // someDir = new File(someDirStr);
      // fileList = someDir.listFiles();
      // if(fileList == null || fileList.length<MAX_DIR_NUM){
      // int secondDirNum = Integer.parseInt(lastDirs[1]);
      // retDirStr =
      // rootDir+lastDirs[0]+"/"+String.valueOf(secondDirNum+1)+"/1/";
      //
      // }else{
      // someDirStr = rootDir;
      // someDir = new File(someDirStr);
      // fileList = someDir.listFiles();
      // if(fileList == null || fileList.length<MAX_DIR_NUM){
      // int firstDirNum = Integer.parseInt(lastDirs[0]);
      // retDirStr = rootDir+String.valueOf(firstDirNum+1)+"/1/1/";
      //
      // }else{
      //
      // }
      // }
      // }
      // }
      // }
      //
      // Editor editor = appSp.edit();
      // editor.putString(CenterPrefConstants.LATEST_MUSIC_DIR, retDirStr);
      // editor.commit();
      // return retDirStr;

      // String retDirStr = null;
      // Random r = new Random();
      // while(true){
      // int num1 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
      // int num2 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
      // int num3 = r.nextInt(MAX_FILE_NUM_PER_DIR)+1;
      // String subDirStr = rootDirStr+num1+"/"+num2+"/"+num3+"/";
      // File subDir = new File(subDirStr);
      // if(subDir.exists()){
      // File[] childFiles = subDir.listFiles();
      // if(childFiles == null || childFiles.length<MAX_FILE_NUM_PER_DIR){
      // retDirStr = subDirStr;
      // break;
      // }
      // }else{
      // retDirStr = subDirStr;
      // break;
      // }
      // }
      //
      // if(MyLog.isDyeLevel()){
      // MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "retDirStr is:"+retDirStr);
      // }
      // return retDirStr;

      String retDirStr = null;
      File rootDir = new File(rootDirStr);
      File[] firstChildFiles = rootDir.listFiles();
      boolean found = false;
      if (firstChildFiles == null || firstChildFiles.length == 0) {
         found = true;
         retDirStr = rootDirStr + "1/1/1/";
      } else {
         int firstSubDirNum = 0;
         FIRST_LOOP: for (int i = 0; i < firstChildFiles.length; i++) {
            File loopFirstChildFile = firstChildFiles[i];
            if (loopFirstChildFile.isDirectory()) {
               firstSubDirNum++;
               File[] loopSecondChildFiles = loopFirstChildFile.listFiles();
               if (loopSecondChildFiles == null || loopSecondChildFiles.length == 0) {
                  found = true;
                  retDirStr = rootDirStr + loopFirstChildFile.getName() + "/1/1/";
                  break;
               } else {
                  int secondSubDirNum = 0;
                  SECOND_LOOP: for (int j = 0; j < loopSecondChildFiles.length; j++) {
                     File loopSecondChildFile = loopSecondChildFiles[j];
                     if (loopSecondChildFile.isDirectory()) {
                        secondSubDirNum++;
                        File[] thirdChildFiles = loopSecondChildFile.listFiles();
                        if (thirdChildFiles == null || thirdChildFiles.length == 0) {
                           found = true;
                           retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
                                 + loopSecondChildFile.getName() + "/1/";
                           break FIRST_LOOP;
                        } else {
                           int thirdSubDirNum = 0;
                           THIRD_LOOP: for (int k = 0; k < thirdChildFiles.length; k++) {
                              File loopThirdChildFile = thirdChildFiles[k];
                              if (loopThirdChildFile.isDirectory()) {
                                 thirdSubDirNum++;
                                 File[] loopForthChildFiles = loopThirdChildFile.listFiles();
                                 if (loopForthChildFiles == null
                                       || loopForthChildFiles.length < MAX_FILE_NUM_PER_DIR) {
                                    found = true;
                                    retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
                                          + loopSecondChildFile.getName() + "/"
                                          + loopThirdChildFile.getName() + "/";
                                    break FIRST_LOOP;
                                 }
                              }
                           }
                           if (thirdSubDirNum < MAX_DIR_NUM) {
                              found = true;
                              retDirStr = rootDirStr + loopFirstChildFile.getName() + "/"
                                    + loopSecondChildFile.getName() + "/" + (thirdSubDirNum + 1) + "/";
                              break FIRST_LOOP;
                           }
                        }
                     }
                  }
                  if (secondSubDirNum < MAX_DIR_NUM) {
                     found = true;
                     retDirStr = rootDirStr + loopFirstChildFile.getName() + "/" + (secondSubDirNum + 1) + "/1/";
                     break FIRST_LOOP;
                  }
               }

            }
         }
         if (!found) {
            if (firstSubDirNum < MAX_DIR_NUM) {
               retDirStr = rootDirStr + (firstSubDirNum + 1) + "/1/1/";
            } else {
               throw new IllegalStateException("file num too many,exceed max save num");
            }
         }
      }
      if (MyLog.isDyeLevel()) {
         MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "retDirStr is:" + retDirStr);
      }
      return retDirStr;

   }

   public static boolean copyFile(File src, File dest, String logTag) {
      FileInputStream fis = null;
      FileOutputStream fos = null;
      if (MyLog.isDyeLevel()) {
         MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "begin copy file");
      }
      if (!dest.exists()) {
         File destPFile = dest.getParentFile();
         if (destPFile != null) {
            destPFile.mkdirs();
         }
      }
      long beginTime = System.currentTimeMillis();
      long srcSize = src.length();
      boolean retValue = false;
      try {
         fis = new FileInputStream(src);
         fos = new FileOutputStream(dest);
         byte[] buffer = new byte[2048 * 100];
         int readByteNum = -1;
         while ((readByteNum = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, readByteNum);
         }
         if (MyLog.isDyeLevel()) {
            long costTime = System.currentTimeMillis() - beginTime;

            MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "srcSize is:" + srcSize + ",costTime is:" + costTime);
         }
         retValue = true;
      } catch (Exception ex) {
         if (MyLog.isDyeLevel()) {
            MyLog.log(logTag, MyLog.DYE_LOG_LEVEL, "copy file failed", ex);
         }
      } finally {
         if (fis != null) {
            try {
               fis.close();
            } catch (IOException ioEx) {

            }
         }
         if (fos != null) {
            try {
               fos.close();
            } catch (IOException ioEx) {

            }
         }
         if (!retValue) {
            if (dest.exists()) {
               dest.delete();
            }
         }
      }
      return retValue;
   }

   public static void deleteDirectory(File dir) {
      if (dir == null) {
         return;
      }
      if (MyLog.isDyeLevel()) {
         MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "deleteDirectory() is called,begin delete file " + dir);
      }
      if (dir.isDirectory()) {
         File[] childFiles = dir.listFiles();
         if (childFiles != null) {
            for (int i = 0; i < childFiles.length; i++) {
               if (childFiles[i].isFile()) {
                  childFiles[i].delete();
               } else {
                  deleteDirectory(childFiles[i]);
               }
            }
         }
         dir.delete();
      } else {
         dir.delete();
      }
   }

   public static void findFileWithSpecialSuffixesList(String path, String[] suffixArray, List<File> foundFileList) {

      if (MyLog.isDyeLevel()) {
         MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "path is:" + path);
      }
      if (path == null || path.trim().length() == 0) {
         return;
      }
      File f = new File(path);
      if (f.isDirectory()) {
         File[] childFiles = f.listFiles();
         if (childFiles != null && childFiles.length > 0) {
            for (int i = 0; i < childFiles.length; i++) {
               File loopFile = childFiles[i];
               if (loopFile.isDirectory()) {
                  findFileWithSpecialSuffixesList(loopFile.getAbsolutePath(), suffixArray, foundFileList);
               } else {
                  if (MyLog.isDyeLevel()) {
                     MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "path is:" + loopFile.getAbsolutePath());
                  }
                  String name = loopFile.getName();
                  int dotIndex = name.lastIndexOf('.');
                  if (dotIndex >= 0) {

                     String loopSuffix = name.substring(dotIndex);

                     if (Arrays.binarySearch(suffixArray, loopSuffix) >= 0) {
                        foundFileList.add(loopFile);
                     }
                  }
               }
            }
         }
      } else {
         String name = f.getName();
         int dotIndex = name.lastIndexOf('.');
         if (dotIndex >= 0) {

            String loopSuffix = name.substring(dotIndex);

            if (Arrays.binarySearch(suffixArray, loopSuffix) >= 0) {
               foundFileList.add(f);
            }
         }
      }
   }

   public static StorageVolume[] getVolumeList() {
      try {
         StorageManager storageManager = (StorageManager) CenterService.getContext()
               .getSystemService(Context.STORAGE_SERVICE);
         Method getVolumeListMethod = storageManager.getClass().getDeclaredMethod("getVolumeList", new Class[] {});
         StorageVolume[] volumeArray = (StorageVolume[]) getVolumeListMethod.invoke(storageManager, new Object[] {});
         return volumeArray;
      } catch (Exception ex) {
         if (MyLog.isDyeLevel()) {
            MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "get volume list fail", ex);
         }
         return null;
      }
   }

   public static String getSecondStoragePath() {
      StorageVolume[] volumeArray = getVolumeList();

      if (volumeArray != null && volumeArray.length > 0) {
         for (int i = 0; i < volumeArray.length; i++) {
            StorageVolume vol = volumeArray[i];
            if (MyLog.isDyeLevel()) {
               MyLog.log(TAG, MyLog.DYE_LOG_LEVEL, "volume path is:" + vol.getPath() + ",isPrimary is:"
                     + vol.isPrimary() + ",isRemovable is:" + vol.isRemovable());
            }
            if (!vol.isPrimary()) {
               return vol.getPath();
            }
         }
      }
      return "";
   }

   /**
    * 按行讀取txt
    * 
    * @param is
    * @return
    * @throws Exception
    */
   public static String readTextFromFile(InputStream is) throws Exception {
      // InputStreamReader reader = new InputStreamReader(is);
      InputStreamReader reader = new InputStreamReader(is, "UTF-8");
      BufferedReader bufferedReader = new BufferedReader(reader);
      StringBuffer buffer = new StringBuffer("");
      String str;
      while ((str = bufferedReader.readLine()) != null) {
         buffer.append(str);
         buffer.append("\n");
      }
      return buffer.toString();
   }

   public static String getUpgradeAppDir() {
      return Environment.getExternalStorageDirectory().getAbsolutePath()+CenterConstants.DISK_ROOT_UPGRADE_CACHE_PATH +"/upgradeapp/";

   }

   public static String getCenterUpgradeDir() {
      return Environment.getExternalStorageDirectory().getAbsolutePath()+CenterConstants.DISK_ROOT_UPGRADE_CACHE_PATH +"/centerapp/";
   }

   public static boolean copyApkFromAssets(Context context, String fileName, String path) {
      boolean copyIsFinish = false;
      try {
         // is =
         // mContext.getResources().getAssets().open("app/MetBaoUpgrade_Signed_1.1.apk");
         InputStream is = context.getResources().getAssets().open(fileName);
         File file = new File(path);
         file.createNewFile();
         FileOutputStream fos = new FileOutputStream(file);
         byte[] temp = new byte[1024];
         int i = 0;
         while ((i = is.read(temp)) > 0) {
            fos.write(temp, 0, i);
         }
         fos.close();
         is.close();
         copyIsFinish = true;
      } catch (IOException e) {
         // e.printStackTrace();
         copyIsFinish = false;
      }
      return copyIsFinish;
   }

   private static final int BUFFER = 8192;

   /**
    * 判斷文件文件是否存在
    * 
    * @param path
    *            文件路徑
    * @return
    */
   public static boolean existFile(String path) {
      String filePath = path;
      File file = new File(filePath);
      if (file.exists()) {
         return true;
      }
      return false;
   }
   
   /**
    * 判斷文件是否存在
    * 
    * @param path
    *            文件路徑
    * @return
    */
   public static boolean isFile(String path) {
      String filePath = path;
      File file = new File(filePath);
      if (file.exists() && file.isFile()) {
         return true;
      }
      return false;
   }
   
   /**
    * 判斷文件是否存在
    * 
    * @param path
    *            文件路徑
    * @return
    */
   public static boolean isFile(File file) {
      if (file.exists() && file.isFile()) {
         return true;
      }
      return false;
   }
   
   /**
    * 判斷文件是否是空文件
    * 
    * @param path
    *            文件路徑
    * @return
    */
   public static boolean isNullFile(String path) {
      String filePath = path;
      File file = new File(filePath);
      if (file.exists() && file.isFile() && file.length()<=0) {
         return true;
      }
      return false;
   }
   
   /**
    * 判斷文件是否是空文件
    * 
    * @param path
    *            文件路徑
    * @return
    */
   public static boolean isNullFile(File file) {
      if (file.exists() && file.isFile() && file.length()<=0) {
         return true;
      }
      return false;
   }

   /**
    * 將字符串寫入指定文件(當指定的父路徑中文件夾不存在時,會最大限度去創建,以保證保存成功!)
    * 
    * @param res
    *            原字符串
    * @param filePath
    *            文件路徑
    * @return 成功標記
    */
   public static boolean string2File(String res, String filePath) {
      boolean flag = true;
      BufferedReader bufferedReader = null;
      BufferedWriter bufferedWriter = null;
      try {
         File distFile = new File(filePath);
         if (!distFile.getParentFile().exists())
            distFile.getParentFile().mkdirs();
         bufferedReader = new BufferedReader(new StringReader(res));
         bufferedWriter = new BufferedWriter(new FileWriter(distFile));
         char buf[] = new char[1024]; // 字符緩衝區
         int len;
         while ((len = bufferedReader.read(buf)) != -1) {
            bufferedWriter.write(buf, 0, len);
         }
         bufferedWriter.flush();
         bufferedReader.close();
         bufferedWriter.close();
      } catch (IOException e) {
         //e.printStackTrace();
         flag = false;
         return flag;
      } finally {
         if (bufferedReader != null) {
            try {
               bufferedReader.close();
            } catch (IOException e) {
               //e.printStackTrace();
               flag = false;
            }
         }
      }
      return flag;
   }

   /**
    * 文本文件轉換爲指定編碼的字符串
    * 
    * @param file
    *            文本文件
    * @param encoding
    *            編碼類型
    * @return 轉換後的字符串
    * @throws java.io.IOException
    */
   public static String file2String(File file, String encoding) {
      InputStreamReader reader = null;
      StringWriter writer = new StringWriter();
      try {
         if (encoding == null || "".equals(encoding.trim())) {
            reader = new InputStreamReader(new FileInputStream(file));
         } else {
            reader = new InputStreamReader(new FileInputStream(file), encoding);
         }
         // 將輸入流寫入輸出流
         char[] buffer = new char[1024];
         int n = 0;
         while (-1 != (n = reader.read(buffer))) {
            writer.write(buffer, 0, n);
         }
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      } finally {
         if (reader != null)
            try {
               reader.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
      }
      // 返回轉換結果
      if (writer != null)
         return writer.toString();
      else
         return null;
   }

   /**
    * 刪除目錄(文件夾)以及目錄下的文件
    * 
    * @param path
    *            被刪除目錄的文件路徑
    * @return 目錄刪除成功返回true,否則返回false
    */
   public static boolean createDirectory(String path) {
      File outFile = new File(path);
      if (!outFile.exists())
         return outFile.mkdirs();
      return true;
   }

   /**
    * 根據路徑刪除指定的目錄或文件,無論存在與否
    * 
    * @param path
    *            要刪除的目錄或文件
    * @return 刪除成功返回 true,否則返回 false。
    */
   public static boolean deleteFolder(String path) {
      boolean flag = false;
      File file = new File(path);
      // 判斷目錄或文件是否存在
      if (!file.exists()) { // 不存在返回 false
         return flag;
      } else {
         // 判斷是否爲文件
         if (file.isFile()) { // 爲文件時調用刪除文件方法
            return deleteFile(path);
         } else { // 爲目錄時調用刪除目錄方法
            return deleteDirectory(path);
         }
      }
   }

   /**
    * 刪除目錄(文件夾)以及目錄下的文件
    * 
    * @param path
    *            被刪除目錄的文件路徑
    * @return 目錄刪除成功返回true,否則返回false
    */
   public static boolean deleteDirectory(String path) {
      // 如果sPath不以文件分隔符結尾,自動添加文件分隔符
      if (!path.endsWith(File.separator)) {
         path = path + File.separator;
      }
      File dirFile = new File(path);
      // 如果dir對應的文件不存在,或者不是一個目錄,則退出
      if (!dirFile.exists() || !dirFile.isDirectory()) {
         return false;
      }
      boolean flag = true;
      // 刪除文件夾下的所有文件(包括子目錄)
      File[] files = dirFile.listFiles();
      if (files != null && files.length > 0) {
         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 path
    *            被刪除文件的文件名
    * @return 單個文件刪除成功返回true,否則返回false
    */
   public static boolean deleteFile(String path) {
      boolean flag = false;
      File file = new File(path);
      // 路徑爲文件且不爲空則進行刪除
      if (file.isFile() && file.exists()) {
         file.delete();
         flag = true;
      }
      return flag;
   }

   // 讀取文件
   public static String readTextFile(File file) throws IOException {
      String text = null;
      InputStream is = null;
      try {
         is = new FileInputStream(file);
         text = readTextInputStream(is);
      } finally {
         if (is != null) {
            is.close();
         }
      }
      return text;
   }

   // 從流中讀取文件
   public static String readTextInputStream(InputStream is) throws IOException {
      StringBuffer strbuffer = new StringBuffer();
      String line;
      BufferedReader reader = null;
      try {
         reader = new BufferedReader(new InputStreamReader(is));
         while ((line = reader.readLine()) != null) {
            strbuffer.append(line).append("\r\n");
         }
      } finally {
         if (reader != null) {
            reader.close();
         }
      }
      return strbuffer.toString();
   }

   // 將文本內容寫入文件
   public static void writeTextFile(File file, String str) throws IOException {
      DataOutputStream out = null;
      try {
         out = new DataOutputStream(new FileOutputStream(file));
         out.write(str.getBytes());
      } finally {
         if (out != null) {
            out.close();
         }
      }
   }

   // 複製文件
   public static void copyFile(File sourceFile, File targetFile) throws IOException {
      BufferedInputStream inBuff = null;
      BufferedOutputStream outBuff = null;
      try {
         inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
         outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
         byte[] buffer = new byte[BUFFER];
         int length;
         while ((length = inBuff.read(buffer)) != -1) {
            outBuff.write(buffer, 0, length);
         }
         outBuff.flush();
      } finally {
         if (inBuff != null) {
            inBuff.close();
         }
         if (outBuff != null) {
            outBuff.close();
         }
      }
   }

   /**
    * 解壓縮
    * 
    * @param zipPathFile
    *            要解壓的文件
    * @param sDestPath
    *            解壓到某文件夾
    * @return
    */
   public static ArrayList decmpression(String zipPathFile, String sDestPath) {
      ArrayList<String> allFileName = new ArrayList<String>();
      try {
         // 先指定壓縮檔的位置和檔名,建立FileInputStream對象
         FileInputStream fins = new FileInputStream(zipPathFile);
         // 將fins傳入ZipInputStream中
         ZipInputStream zins = new ZipInputStream(fins);
         ZipEntry ze = null;
         byte[] ch = new byte[256];
         while ((ze = zins.getNextEntry()) != null) {
            File zfile = new File(sDestPath + ze.getName());
            File fpath = new File(zfile.getParentFile().getPath());
            if (ze.isDirectory()) {
               if (!zfile.exists())
                  zfile.mkdirs();
               zins.closeEntry();
            } else {
               if (!fpath.exists())
                  fpath.mkdirs();
               FileOutputStream fouts = new FileOutputStream(zfile);
               int i;
               allFileName.add(zfile.getAbsolutePath());
               while ((i = zins.read(ch)) != -1)
                  fouts.write(ch, 0, i);
               zins.closeEntry();
               fouts.close();
            }
         }
         fins.close();
         zins.close();
      } catch (Exception e) {
         System.err.println("Extract error:" + e.getMessage());
      }
      return allFileName;
   }

   /**
    * 解壓縮
    * 
    * @param zipFile
    *            要解壓的文件
    * @param destPath
    *            解壓到某文件夾
    * @return
    */
   public static ArrayList decmpression(File zipFile, String destPath) {
      ArrayList<String> allFileName = new ArrayList<String>();
      try {
         // 先指定壓縮檔的位置和檔名,建立FileInputStream對象
         FileInputStream fins = new FileInputStream(zipFile);
         // 將fins傳入ZipInputStream中
         ZipInputStream zins = new ZipInputStream(fins);
         ZipEntry ze = null;
         byte[] ch = new byte[256];
         while ((ze = zins.getNextEntry()) != null) {
            File zfile = new File(destPath + ze.getName());
            File fpath = new File(zfile.getParentFile().getPath());
            if (ze.isDirectory()) {
               if (!zfile.exists())
                  zfile.mkdirs();
               zins.closeEntry();
            } else {
               if (!fpath.exists())
                  fpath.mkdirs();
               FileOutputStream fouts = new FileOutputStream(zfile);
               int i;
               allFileName.add(zfile.getAbsolutePath());
               while ((i = zins.read(ch)) != -1)
                  fouts.write(ch, 0, i);
               zins.closeEntry();
               fouts.close();
            }
         }
         fins.close();
         zins.close();
      } catch (Exception e) {
         System.err.println("Extract error:" + e.getMessage());
      }
      return allFileName;
   }
   /*
    * public long getFileSizes(File f) throws Exception{//取得文件大小 long s=0; if
    * (f.exists()) { FileInputStream fis = null; fis = new FileInputStream(f);
    * s= fis.available(); } else { f.createNewFile();
    * System.out.println("文件不存在"); } return s; }
    */

   // 遞歸取得文件夾(包括子目錄)中所有文件的大小
   public static long getFileSize(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 + getFileSize(flist[i]);
         } else {
            size = size + flist[i].length();
         }
      }
      return size;
   }

   public static String FormetFileSize(long fileS) {// 轉換文件大小
      DecimalFormat df = new DecimalFormat("#.00");
      String fileSizeString = "";
      if (fileS < 1024) {
         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;
   }

   public static long getlist(File f) {// 遞歸求取目錄文件個數
      long size = 0;
      File flist[] = f.listFiles();
      size = flist.length;
      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory()) {
            size = size + getlist(flist[i]);
            size--;
         }
      }
      return size;
   }

   public static long getDir(File f) {// 遞歸求取目錄中文件(包括目錄)的個數
      long size = 0;
      File flist[] = f.listFiles();
      size = flist.length;
      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory()) {
            size = size + getDir(flist[i]);

         }
      }
      return size;
   }

   public static long getRootDirCount(File f) {// 遞歸求取目錄中目錄(不包括子目錄)的個數
      long size = 0;
      File flist[] = f.listFiles();
      size = flist.length;
      if (f == null || !f.isDirectory())
         return 0;
      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory())
            size = size + 1;
      }
      return size;
   }

   public static List<String> getRootDirs(File f) {// 遞歸求取目錄中目錄(不包括子目錄)的目錄名稱信息
      List<String> dirs = new ArrayList<String>();
      long size = 0;
      File flist[] = f.listFiles();
      size = flist.length;
      if (f == null || !f.isDirectory())
         dirs = null;

      for (int i = 0; i < flist.length; i++) {
         if (flist[i].isDirectory())
            dirs.add(flist[i].getName());
      }
      return dirs.isEmpty() ? null : dirs;
   }

   public static void main(String args[]) {
      FileUtil g = new FileUtil();
      long startTime = System.currentTimeMillis();
      try {
         long l = 0;
         String path = "D:\\tomcat7\\webapps\\cwbwebhome";
         File ff = new File(path);
         if (ff.isDirectory()) { // 如果路徑是文件夾的時候
            System.out.println("文件個數           " + g.getlist(ff));
            System.out.println("文件和目錄總個數           " + g.getDir(ff));

            System.out.println("目錄");
            l = g.getFileSize(ff);
            System.out.println(path + "目錄的大小爲:" + g.FormetFileSize(l));
         } else {
            System.out.println("     文件個數           1");
            System.out.println("文件");
            l = g.getFileSize(ff);
            System.out.println(path + "文件的大小爲:" + g.FormetFileSize(l));
         }

      } catch (Exception e) {
         e.printStackTrace();
      }
      long endTime = System.currentTimeMillis();
      System.out.println("總共花費時間爲:" + (endTime - startTime) + "毫秒...");

   }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章