java文件操作(FileUtil .java)

package common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * File Common Class
 *
 * @copyright delicioussmoke
 * @author smoke
 * @date 2006/1/1
 * @version 1.0.0
 * @since
 */
public class FileUtil {

    /**
     * File exist check
     *
     * @param sFileName File Name
     * @return boolean true - exist<br>
     *                 false - not exist
     */
    public static boolean checkExist(String sFileName) {
     
     boolean result = false;
       
        try {
   File f = new File(sFileName);
   
   //if (f.exists() && f.isFile() && f.canRead()) {
   if (f.exists() && f.isFile()) {
    result = true;
   } else {
    result = false;
   }
        } catch (Exception e) {
         result = false;
        }
       
        /* return */
        return result;
    }
   
    /**
     * Get File Size
     *
     * @param sFileName File Name
     * @return long File's size(byte) when File not exist return -1
     */
    public static long getSize(String sFileName) {
       
        long lSize = 0;
       
        try {
   File f = new File(sFileName);
           
            //exist
            if (f.exists()) {
    if (f.isFile() && f.canRead()) {
     lSize = f.length();
    } else {
     lSize = -1;
    }
            //not exist
            } else {
    lSize = 0;
            }
        } catch (Exception e) {
   lSize = -1;
        }
       
        /* return */
        return lSize;
    }
   
 /**
  * File Delete
  *
  * @param sFileName File Nmae
  * @return boolean true - Delete Success<br>
  *                 false - Delete Fail
  */
    public static boolean deleteFromName(String sFileName) {
  
  boolean bReturn = true;
  
  try {
   File oFile = new File(sFileName);
   
   //exist
   if (oFile.exists()) {
    //Delete File
       boolean bResult = oFile.delete();
       //Delete Fail
       if (bResult == false) {
     bReturn = false;
       }
   
   //not exist
   } else {
    
   }
   
  } catch (Exception e) {
   bReturn = false;
  }
  
  //return
  return bReturn;
    }
   
 /**
  * File Unzip
  *
  * @param sToPath  Unzip Directory path
  * @param sZipFile Unzip File Name
  */
 public static void releaseZip(String sToPath, String sZipFile) throws Exception {
  
  if (null == sToPath ||("").equals(sToPath.trim())) {
   File objZipFile = new File(sZipFile);
   sToPath = objZipFile.getParent();
  }
  ZipFile zfile = new ZipFile(sZipFile);
  Enumeration zList = zfile.entries();
  ZipEntry ze = null;
  byte[] buf = new byte[1024];
  while (zList.hasMoreElements()) {

   ze = (ZipEntry) zList.nextElement();
   if (ze.isDirectory()) {
    continue;
   }

   OutputStream os =
    new BufferedOutputStream(
     new FileOutputStream(
      getRealFileName(sToPath, ze.getName())));
   InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
   int readLen = 0;
   while ((readLen = is.read(buf, 0, 1024)) != -1) {
    os.write(buf, 0, readLen);
   }
   is.close();
   os.close();
  }
  zfile.close();
 }
 
 /**
  * getRealFileName
  *
  * @param  baseDir   Root Directory
  * @param  absFileName  absolute Directory File Name
  * @return java.io.File     Return file
  */
 private static File getRealFileName(String baseDir, String absFileName) throws Exception {
  
  File ret = null;

  List dirs = new ArrayList();
  StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));
  while (st.hasMoreTokens()) {
   dirs.add(st.nextToken());
  }

  ret = new File(baseDir);
  if (dirs.size() > 1) {
   for (int i = 0; i < dirs.size() - 1; i++) {
    ret = new File(ret, (String) dirs.get(i));
   }
  }
  if (!ret.exists()) {
   ret.mkdirs();
  }
  ret = new File(ret, (String) dirs.get(dirs.size() - 1));
  return ret;
 }

 /**
  * copyFile
  *
  * @param  srcFile   Source File
  * @param  targetFile   Target file
  */
 static public void copyFile(String srcFile , String targetFile) throws IOException
  {
  
   FileInputStream reader = new FileInputStream(srcFile);
   FileOutputStream writer = new FileOutputStream(targetFile);

   byte[] buffer = new byte [4096];
   int len;

   try
   {
    reader = new FileInputStream(srcFile);
    writer = new FileOutputStream(targetFile);
   
    while((len = reader.read(buffer)) > 0)
    {
     writer.write(buffer , 0 , len);
    }
   }
   catch(IOException e)
   {
    throw e;
   }
   finally
   {
    if (writer != null)writer.close();
    if (reader != null)reader.close();
   }
  }

 /**
  * renameFile
  *
  * @param  srcFile   Source File
  * @param  targetFile   Target file
  */
 static public void renameFile(String srcFile , String targetFile) throws IOException
  {
   try {
    copyFile(srcFile,targetFile);
    deleteFromName(srcFile);
   } catch(IOException e){
    throw e;
   }
  }


 public static void write(String tivoliMsg,String logFileName) {
  try{
   byte[]  bMsg = tivoliMsg.getBytes();
   FileOutputStream fOut = new FileOutputStream(logFileName, true);
   fOut.write(bMsg);
   fOut.close();
  } catch(IOException e){
   //throw the exception      
  }

 }
 /**
 * This method is used to log the messages with timestamp,error code and the method details
 * @param errorCd String
 * @param className String
 * @param methodName String
 * @param msg String
 */
 public static void writeLog(String logFile, String batchId, String exceptionInfo) {
  
  DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);
  
  Object args[] = {df.format(new Date()), batchId, exceptionInfo};
  
  String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);
  
  try {
   
   File logfile = new File(logFile);
   if(!logfile.exists()) {
    logfile.createNewFile();
   }
   
      FileWriter fw = new FileWriter(logFile, true);
      fw.write(fmtMsg);
      fw.write(System.getProperty("line.separator"));

      fw.flush();
      fw.close();

  } catch(Exception e) {
  }
 }
}

阅读更多
个人分类: JAVA
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭