FileUtil(File处理工具类,copy,压缩,删除等)

 

File处理工具

Java代码   收藏代码
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.FileWriter;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.io.InputStreamReader;  
  12. import java.io.OutputStream;  
  13. import java.text.DateFormat;  
  14. import java.text.MessageFormat;  
  15. import java.util.ArrayList;  
  16. import java.util.Date;  
  17. import java.util.Enumeration;  
  18. import java.util.List;  
  19. import java.util.Locale;  
  20. import java.util.StringTokenizer;  
  21. import java.util.zip.ZipEntry;  
  22. import java.util.zip.ZipFile;  
  23.   
  24. /** 
  25.  *  
  26.  * @author IBM 
  27.  *  
  28.  */  
  29.   
  30. public class FileUtil {  
  31.       
  32.     public static String dirSplit = "\\";//linux windows  
  33.     /** 
  34.      * save file accroding to physical directory infomation 
  35.      *  
  36.      * @param physicalDir 
  37.      *            physical directory 
  38.      * @param fname 
  39.      *            file name of destination 
  40.      * @param istream 
  41.      *            input stream of destination file 
  42.      * @return 
  43.      */  
  44.   
  45.     public static boolean SaveFileByPhysicalDir(String physicalPath,  
  46.             InputStream istream) {  
  47.           
  48.         boolean flag = false;  
  49.         try {  
  50.             OutputStream os = new FileOutputStream(physicalPath);  
  51.             int readBytes = 0;  
  52.             byte buffer[] = new byte[8192];  
  53.             while ((readBytes = istream.read(buffer, 08192)) != -1) {  
  54.                 os.write(buffer, 0, readBytes);  
  55.             }  
  56.             os.close();  
  57.             flag = true;  
  58.         } catch (FileNotFoundException e) {  
  59.               
  60.             e.printStackTrace();  
  61.         } catch (IOException e) {  
  62.           
  63.             e.printStackTrace();  
  64.         }  
  65.         return flag;  
  66.     }  
  67.       
  68.     public static boolean CreateDirectory(String dir){  
  69.         File f = new File(dir);  
  70.         if (!f.exists()) {  
  71.             f.mkdirs();  
  72.         }  
  73.         return true;  
  74.     }  
  75.       
  76.       
  77.     public static void saveAsFileOutputStream(String physicalPath,String content) {  
  78.           File file = new File(physicalPath);  
  79.           boolean b = file.getParentFile().isDirectory();  
  80.           if(!b){  
  81.               File tem = new File(file.getParent());  
  82.               // tem.getParentFile().setWritable(true);  
  83.               tem.mkdirs();// 创建目录  
  84.           }  
  85.           //Log.info(file.getParent()+";"+file.getParentFile().isDirectory());  
  86.           FileOutputStream foutput =null;  
  87.           try {  
  88.               foutput = new FileOutputStream(physicalPath);  
  89.                 
  90.               foutput.write(content.getBytes("UTF-8"));  
  91.               //foutput.write(content.getBytes());  
  92.           }catch(IOException ex) {  
  93.               ex.printStackTrace();  
  94.               throw new RuntimeException(ex);  
  95.           }finally{  
  96.               try {  
  97.                   foutput.flush();  
  98.                   foutput.close();  
  99.               }catch(IOException ex){  
  100.                   ex.printStackTrace();  
  101.                   throw new RuntimeException(ex);  
  102.               }  
  103.           }  
  104.             //Log.info("文件保存成功:"+ physicalPath);  
  105.          }  
  106.   
  107.       
  108.       
  109.      /** 
  110.      * COPY文件 
  111.      * @param srcFile String 
  112.      * @param desFile String 
  113.      * @return boolean 
  114.      */  
  115.     public boolean copyToFile(String srcFile, String desFile) {  
  116.         File scrfile = new File(srcFile);  
  117.         if (scrfile.isFile() == true) {  
  118.             int length;  
  119.             FileInputStream fis = null;  
  120.             try {  
  121.                 fis = new FileInputStream(scrfile);  
  122.             }  
  123.             catch (FileNotFoundException ex) {  
  124.                 ex.printStackTrace();  
  125.             }  
  126.             File desfile = new File(desFile);  
  127.   
  128.             FileOutputStream fos = null;  
  129.             try {  
  130.                 fos = new FileOutputStream(desfile, false);  
  131.             }  
  132.             catch (FileNotFoundException ex) {  
  133.                 ex.printStackTrace();  
  134.             }  
  135.             desfile = null;  
  136.             length = (int) scrfile.length();  
  137.             byte[] b = new byte[length];  
  138.             try {  
  139.                 fis.read(b);  
  140.                 fis.close();  
  141.                 fos.write(b);  
  142.                 fos.close();  
  143.             }  
  144.             catch (IOException e) {  
  145.                 e.printStackTrace();  
  146.             }  
  147.         } else {  
  148.             scrfile = null;  
  149.             return false;  
  150.         }  
  151.         scrfile = null;  
  152.         return true;  
  153.     }  
  154.   
  155.     /** 
  156.      * COPY文件夹 
  157.      * @param sourceDir String 
  158.      * @param destDir String 
  159.      * @return boolean 
  160.      */  
  161.     public boolean copyDir(String sourceDir, String destDir) {  
  162.         File sourceFile = new File(sourceDir);  
  163.         String tempSource;  
  164.         String tempDest;  
  165.         String fileName;  
  166.         File[] files = sourceFile.listFiles();  
  167.         for (int i = 0; i < files.length; i++) {  
  168.             fileName = files[i].getName();  
  169.             tempSource = sourceDir + "/" + fileName;  
  170.             tempDest = destDir + "/" + fileName;  
  171.             if (files[i].isFile()) {  
  172.                 copyToFile(tempSource, tempDest);  
  173.             } else {  
  174.                 copyDir(tempSource, tempDest);  
  175.             }  
  176.         }  
  177.         sourceFile = null;  
  178.         return true;  
  179.     }  
  180.   
  181.     /** 
  182.      * 删除指定目录及其中的所有内容。 
  183.      * @param dir 要删除的目录 
  184.      * @return 删除成功时返回true,否则返回false。 
  185.      */  
  186.     public boolean deleteDirectory(File dir) {  
  187.         File[] entries = dir.listFiles();  
  188.         int sz = entries.length;  
  189.         for (int i = 0; i < sz; i++) {  
  190.             if (entries[i].isDirectory()) {  
  191.                 if (!deleteDirectory(entries[i])) {  
  192.                     return false;  
  193.                 }  
  194.             } else {  
  195.                 if (!entries[i].delete()) {  
  196.                     return false;  
  197.                 }  
  198.             }  
  199.         }  
  200.         if (!dir.delete()) {  
  201.             return false;  
  202.         }  
  203.         return true;  
  204.     }  
  205.       
  206.       
  207.       
  208.     /** 
  209.      * File exist check 
  210.      * 
  211.      * @param sFileName File Name 
  212.      * @return boolean true - exist<br> 
  213.      *                 false - not exist 
  214.      */  
  215.     public static boolean checkExist(String sFileName) {  
  216.        
  217.      boolean result = false;  
  218.          
  219.        try {  
  220.            File f = new File(sFileName);  
  221.          
  222.            //if (f.exists() && f.isFile() && f.canRead()) {  
  223.        if (f.exists() && f.isFile()) {  
  224.             result = true;  
  225.        } else {  
  226.             result = false;  
  227.        }  
  228.        } catch (Exception e) {  
  229.             result = false;  
  230.        }  
  231.              
  232.         /* return */  
  233.         return result;  
  234.     }  
  235.      
  236.     /** 
  237.      * Get File Size 
  238.      * 
  239.      * @param sFileName File Name 
  240.      * @return long File's size(byte) when File not exist return -1 
  241.      */  
  242.     public static long getSize(String sFileName) {  
  243.          
  244.         long lSize = 0;  
  245.          
  246.         try {  
  247.             File f = new File(sFileName);  
  248.                      
  249.                     //exist  
  250.             if (f.exists()) {  
  251.                 if (f.isFile() && f.canRead()) {  
  252.                  lSize = f.length();  
  253.                 } else {  
  254.                  lSize = -1;  
  255.                 }  
  256.                     //not exist  
  257.             } else {  
  258.                 lSize = 0;  
  259.             }  
  260.        } catch (Exception e) {  
  261.             lSize = -1;  
  262.        }  
  263.        /* return */  
  264.        return lSize;  
  265.     }  
  266.      
  267.  /** 
  268.   * File Delete 
  269.   * 
  270.   * @param sFileName File Nmae 
  271.   * @return boolean true - Delete Success<br> 
  272.   *                 false - Delete Fail 
  273.   */  
  274.     public static boolean deleteFromName(String sFileName) {  
  275.     
  276.         boolean bReturn = true;  
  277.     
  278.         try {  
  279.             File oFile = new File(sFileName);  
  280.      
  281.            //exist  
  282.            if (oFile.exists()) {  
  283.                //Delete File  
  284.                boolean bResult = oFile.delete();  
  285.                //Delete Fail  
  286.                if (bResult == false) {  
  287.                    bReturn = false;  
  288.                }  
  289.          
  290.                //not exist  
  291.            } else {  
  292.       
  293.            }  
  294.      
  295.       } catch (Exception e) {  
  296.           bReturn = false;  
  297.       }  
  298.     
  299.       //return  
  300.       return bReturn;  
  301.     }  
  302.      
  303.  /** 
  304.   * File Unzip 
  305.   * 
  306.   * @param sToPath  Unzip Directory path 
  307.   * @param sZipFile Unzip File Name 
  308.   */  
  309.  @SuppressWarnings("rawtypes")  
  310. public static void releaseZip(String sToPath, String sZipFile) throws Exception {  
  311.     
  312.   if (null == sToPath ||("").equals(sToPath.trim())) {  
  313.        File objZipFile = new File(sZipFile);  
  314.        sToPath = objZipFile.getParent();  
  315.   }  
  316.   ZipFile zfile = new ZipFile(sZipFile);  
  317.   Enumeration zList = zfile.entries();  
  318.   ZipEntry ze = null;  
  319.   byte[] buf = new byte[1024];  
  320.   while (zList.hasMoreElements()) {  
  321.   
  322.        ze = (ZipEntry) zList.nextElement();  
  323.        if (ze.isDirectory()) {  
  324.         continue;  
  325.        }  
  326.       
  327.        OutputStream os =  
  328.        new BufferedOutputStream(  
  329.        new FileOutputStream(getRealFileName(sToPath, ze.getName())));  
  330.        InputStream is = new BufferedInputStream(zfile.getInputStream(ze));  
  331.        int readLen = 0;  
  332.        while ((readLen = is.read(buf, 01024)) != -1) {  
  333.            os.write(buf, 0, readLen);  
  334.        }  
  335.        is.close();  
  336.        os.close();  
  337.   }  
  338.   zfile.close();  
  339.  }  
  340.    
  341.  /** 
  342.   * getRealFileName 
  343.   * 
  344.   * @param  baseDir   Root Directory 
  345.   * @param  absFileName  absolute Directory File Name 
  346.   * @return java.io.File     Return file 
  347.   */  
  348.  @SuppressWarnings({ "rawtypes""unchecked" })  
  349. private static File getRealFileName(String baseDir, String absFileName) throws Exception {  
  350.     
  351.   File ret = null;  
  352.   
  353.   List dirs = new ArrayList();  
  354.   StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));  
  355.   while (st.hasMoreTokens()) {  
  356.       dirs.add(st.nextToken());  
  357.   }  
  358.   
  359.   ret = new File(baseDir);  
  360.   if (dirs.size() > 1) {  
  361.       for (int i = 0; i < dirs.size() - 1; i++) {  
  362.           ret = new File(ret, (String) dirs.get(i));  
  363.       }  
  364.   }  
  365.   if (!ret.exists()) {  
  366.       ret.mkdirs();  
  367.   }  
  368.   ret = new File(ret, (String) dirs.get(dirs.size() - 1));  
  369.   return ret;  
  370.  }  
  371.   
  372.  /** 
  373.   * copyFile 
  374.   * 
  375.   * @param  srcFile   Source File 
  376.   * @param  targetFile   Target file 
  377.   */  
  378.  @SuppressWarnings("resource")  
  379.  static public void copyFile(String srcFile , String targetFile) throws IOException  
  380.   {  
  381.     
  382.    FileInputStream reader = new FileInputStream(srcFile);  
  383.    FileOutputStream writer = new FileOutputStream(targetFile);  
  384.   
  385.    byte[] buffer = new byte [4096];  
  386.    int len;  
  387.   
  388.    try  
  389.    {  
  390.        reader = new FileInputStream(srcFile);  
  391.        writer = new FileOutputStream(targetFile);  
  392.          
  393.        while((len = reader.read(buffer)) > 0)  
  394.        {  
  395.            writer.write(buffer , 0 , len);  
  396.        }  
  397.    }  
  398.    catch(IOException e)  
  399.    {  
  400.        throw e;  
  401.    }  
  402.    finally  
  403.    {  
  404.        if (writer != null)writer.close();  
  405.        if (reader != null)reader.close();  
  406.    }  
  407.   }  
  408.   
  409.  /** 
  410.   * renameFile 
  411.   * 
  412.   * @param  srcFile   Source File 
  413.   * @param  targetFile   Target file 
  414.   */  
  415.  static public void renameFile(String srcFile , String targetFile) throws IOException  
  416.   {  
  417.    try {  
  418.        copyFile(srcFile,targetFile);  
  419.        deleteFromName(srcFile);  
  420.    } catch(IOException e){  
  421.        throw e;  
  422.    }  
  423.   }  
  424.   
  425.   
  426.  public static void write(String tivoliMsg,String logFileName) {  
  427.   try{  
  428.        byte[]  bMsg = tivoliMsg.getBytes();  
  429.        FileOutputStream fOut = new FileOutputStream(logFileName, true);  
  430.        fOut.write(bMsg);  
  431.        fOut.close();  
  432.   } catch(IOException e){  
  433.    //throw the exception        
  434.   }  
  435.   
  436.  }  
  437.  /** 
  438.  * This method is used to log the messages with timestamp,error code and the method details 
  439.  * @param errorCd String 
  440.  * @param className String 
  441.  * @param methodName String 
  442.  * @param msg String 
  443.  */  
  444.  public static void writeLog(String logFile, String batchId, String exceptionInfo) {  
  445.     
  446.   DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);  
  447.     
  448.   Object args[] = {df.format(new Date()), batchId, exceptionInfo};  
  449.     
  450.   String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);  
  451.     
  452.   try {  
  453.      
  454.    File logfile = new File(logFile);  
  455.    if(!logfile.exists()) {  
  456.     logfile.createNewFile();  
  457.    }  
  458.      
  459.       FileWriter fw = new FileWriter(logFile, true);  
  460.       fw.write(fmtMsg);  
  461.       fw.write(System.getProperty("line.separator"));  
  462.   
  463.       fw.flush();  
  464.       fw.close();  
  465.   
  466.   } catch(Exception e) {  
  467.   }  
  468.  }  
  469.    
  470.  public static String readTextFile(String realPath) throws Exception {  
  471.      File file = new File(realPath);  
  472.         if (!file.exists()){  
  473.             System.out.println("File not exist!");  
  474.             return null;  
  475.       }  
  476.       BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"UTF-8"));     
  477.       String temp = "";  
  478.       String txt="";  
  479.       while((temp = br.readLine()) != null){  
  480.           txt+=temp;  
  481.        }        
  482.       br.close();  
  483.      return txt;  
  484.  }  
  485.   
  486.    
  487. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值