fileUtil

/**
 * 文件名:  FileUtils.java
 * 版權:    Copyright 2000-2009 Huawei Tech. Co. Ltd. All Rights Reserved.
 * 創建人:  005828
 * 文件描述:  
 * 修改時間: 2010-4-20 下午03:06:18
 * 修改內容: 新增
 */
package com.huawei.srcms.common.util;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
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.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.huawei.srcms.common.constant.CharEncoding;
import com.huawei.srcms.common.constant.ErrorCode;
import com.huawei.srcms.common.constant.SRCMSConstant;
import com.huawei.srcms.common.exception.SRCMSException;
import com.huawei.srcms.common.exception.SRCMSServiceException;


/**
 * 
 * 類描述:文件處理工具類
 * 
 * @author 005828
 * @version srcms V2R1C01B01
 */
public class FileUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
    
    /**
     * 安全路徑正則表達式
     */
    private static final Pattern SAFE_PATH_PATTERN = Pattern
            .compile("(.*([/\\\\]{1}[\\.\\.]{1,2}|[\\.\\.]{1,2}[/\\\\]{1}|\\.\\.).*|\\.)");
            
    //讀取文件字節最大大小
    private static final long FILE_READ_MAX_SIZE = 52428800;
    
    /**
     * 路徑是否是安全路徑
     * 
     * @param filePath
     * @return
     */
    public static boolean isSafePath(final String filePath)
    {
        if (StringUtils.isBlank(filePath))
        {
            return false;
        }
        
        Matcher matcher = SAFE_PATH_PATTERN.matcher(filePath);
        boolean isSafe = !matcher.matches();
        return isSafe;
    }
    
    /**
     * 
     * 檢測zip內文件路徑
     * 
     * @param sZipPathFile zip源文件(包括文件名)
     * @param destDir zip目標文件的路徑,以‘/’結尾
     * @return void
     */
    public static boolean validZipPackage(String zipfile, String destDir)
    {
        boolean blret = true;
        
        ZipFile zipFile = null;
        
        try
        {
            zipFile = new ZipFile(new File(zipfile), "UTF-8");
            
            Enumeration<?> enumeration = zipFile.getEntries();
            ZipEntry zipEntry = null;
            
            while (enumeration.hasMoreElements())
            {
                zipEntry = (ZipEntry)enumeration.nextElement();
                
                //取文件絕對路徑
                File loadFile = new File(destDir + "/" + zipEntry.getName());
                String loadFileDir = loadFile.getCanonicalPath();
                
                //取目錄絕對路徑
                File loadDir = new File(destDir);
                String loadDirDir = loadDir.getCanonicalPath();
                
                //路徑不匹配,則失敗
                if (!loadFileDir.startsWith(loadDirDir))
                {
                    blret = false;
                    LOGGER.error("Error filepath:" + loadFileDir + " not in InputDir:" + loadDirDir);
                    break;
                }
            }
        }
        catch (IOException e)
        {
            throw new SRCMSServiceException(ErrorCode.COMMON_ERROR_UNDEFINED, "Check zip file path failed.", e);
        }
        finally
        {
            try
            {
                if (null != zipFile)
                {
                    zipFile.close();
                }
            }
            catch (IOException e)
            {
                LOGGER.error("Close ZipFile failed, message:" + e.getMessage());
            }
        }
        
        return blret;
    }
    
    /**
     * 
     * 解壓zip文件
     * 
     * @param sZipPathFile zip源文件(包括文件名)
     * @param destDir zip目標文件的路徑
     * @return void
     * @throws IOException
     */
    public static void unzip(String zipfile, String unzipPath)
    {
        unzipPath = unzipPath.endsWith(File.separator) ? unzipPath : unzipPath + File.separator;
        byte b[] = new byte[1024];
        int length;
        ZipFile zipFile = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        
        try
        {
            // 判斷是否配置瞭解壓類型
            String decodeCharset = "UTF-8";
            if (CommonUtil.isNull(decodeCharset))
            {
                zipFile = new ZipFile(new File(zipfile));
            }
            else
            {
                zipFile = new ZipFile(new File(zipfile), decodeCharset.trim());
            }
            
            Enumeration<?> enumeration = zipFile.getEntries();
            ZipEntry zipEntry = null;
            
            while (enumeration.hasMoreElements())
            {
                zipEntry = (ZipEntry)enumeration.nextElement();
                File loadFile = new File(unzipPath + zipEntry.getName());
                if (zipEntry.isDirectory())
                {
                    if (!loadFile.exists())
                    {
                        boolean ok = loadFile.mkdirs();
                        if (!ok)
                        {
                            throw new SRCMSServiceException(ErrorCode.COMMON_ERROR_UNDEFINED, "Create directory failed.");
                        }
                    }
                }
                else
                {
                    File parentFile = loadFile.getParentFile();
                    if (null == parentFile)
                    {
                        LOGGER.error("Obtain parent file failed.");
                        continue;
                    }
                    
                    if (!parentFile.exists())
                    {
                        boolean ok = parentFile.mkdirs();
                        if (!ok)
                        {
                            throw new SRCMSServiceException(ErrorCode.COMMON_ERROR_UNDEFINED, "Create directory failed.");
                        }
                    }
                    
                    inputStream = zipFile.getInputStream(zipEntry);
                    if (null == inputStream)
                    {
                        LOGGER.error("Obtain inputstream failed.");
                        continue;
                    }
                    
                    outputStream = new FileOutputStream(loadFile);
                    
                    while ((length = inputStream.read(b)) > 0)
                    {
                        outputStream.write(b, 0, length);
                    }
                    
                    outputStream.flush();
                    inputStream.close();
                    outputStream.close();
                }
            }
            
            zipFile.close();
        }
        catch (IOException e)
        {
            throw new SRCMSServiceException(ErrorCode.COMMON_ERROR_UNDEFINED, "Unzip file failed.", e);
        }
        finally
        {
            try
            {
                if (null != zipFile)
                {
                    zipFile.close();
                }
            }
            catch (IOException e)
            {
                LOGGER.error("Close ZipFile failed, message:" + e.getMessage());
            }
            
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }
    
    /**
     * 刪除文件,如果是文件夾則將刪除文件夾下的所有文件
     * 
     * @param file
     * 
     */
    public static void deleteFile(File file)
    {
        if (!file.exists())
        {
            return;
        }
        
        if (file.isDirectory())
        {
            File[] files = file.listFiles();
            if (null != files)
            {
                for (File subFile : files)
                {
                    deleteFile(subFile);
                }
            }
        }
        else
        {
            boolean ok = file.delete();
            if (!ok)
            {
                LOGGER.error("Delete file failed.");
            }
        }
    }
    
    public static void deleteFile(String file)
    {
        deleteFile(new File(file));
    }
    
    /**
     * 讀取文本文件
     * 
     * @param filePath
     * @return String
     * @throws SRCMSException 
     */
    public static String readEmailTemplateFile(String filePath) throws SRCMSException
    {
        BufferedReader reader = null;
        BoundedInputStream boundedInput = null;
        InputStream istream = null;
        
        try
        {
            StringBuffer content = new StringBuffer();
            
            istream = new FileInputStream(filePath);
            boundedInput = new BoundedInputStream(istream, FILE_READ_MAX_SIZE);
            reader = new BufferedReader(new InputStreamReader(boundedInput, CharEncoding.UTF_8));
            
            String tempString = null;
            while ((tempString = reader.readLine()) != null)
            {
                content.append(tempString);
            }
            
            return content.toString();
        }
        catch (IOException e)
        {
            throw new SRCMSException(e.getMessage(), e);
        }
        finally
        {
            IOUtils.closeQuietly(istream);
            IOUtils.closeQuietly(boundedInput);
            IOUtils.closeQuietly(reader);
        }
    }
    
    /**
     * 
     * copyFileToDir
     * 
     * @param srcFile
     * @param desDir
     * @throws IOException
     */
    public static void copyFileToDir(String srcFile, String desDir) throws IOException
    {
        org.apache.commons.io.FileUtils.copyFileToDirectory(new File(srcFile), new File(desDir));
    }
    
    /**
     * 
     * 刪除某路徑下的所有文件及文件夾
     * 
     * @param path 路徑
     * @param deletRootDir 是否刪除path目錄
     * @return boolean
     */
    public static boolean deleteFiles(String path)
    {
        try
        {
            if (SRCMSUtils.isNull(path))
            {
                return false;
            }
            
            File file = new File(path);
            if (!file.exists())
            {
                return false;
            }
            
            File[] subFiles = file.listFiles();
            if (null == subFiles || subFiles.length == 0)
            {
                return false;
            }
            
            for (int i = 0; i < subFiles.length; i++)
            {
                if (subFiles[i].isDirectory())
                {
                    deleteFiles(subFiles[i].getPath());
                    
                    boolean ok = subFiles[i].delete();
                    if (!ok)
                    {
                        LOGGER.error("Delete file failed.");
                        return false;
                    }
                }
                else
                {
                    boolean ok = subFiles[i].delete();
                    if (!ok)
                    {
                        LOGGER.error("Delete file failed.");
                        return false;
                    }
                }
            }
            
            boolean ok = file.delete();
            if (!ok)
            {
                LOGGER.error("Delete file failed.");
                return false;
            }
        }
        catch (Throwable e)
        {
            throw new SRCMSServiceException(ErrorCode.COMMON_ERROR_UNDEFINED, "delete Files failed for Exception");
        }
        
        return true;
    }
    
    /**
     * 方法表述
     * 
     * @param uploadPath
     * @return String
     */
    /**
     * 
     * 獲取指定字符串的文件名稱
     * 
     * @param path
     */
    
    public static String getFileNamebyPath(String path)
    {
        path = path.replaceAll("\\\\", "/");
        String name[] = path.split("/");
        int i = name.length - 1;
        return name[i];
    }
    
    /**
     * 
     * 方法表述 對url進行編碼
     * @param urlStr
     * @return String
     */
    public static String encodingURL(String urlStr)
    {
        StringBuffer buff = new StringBuffer();
        String encodedUrl = "";
        try
        {
            if (SRCMSUtils.isNull(urlStr))
            {
                return encodedUrl;
            }
            
            int position = urlStr.indexOf("?");
            String uri = position == -1 ? urlStr : urlStr.substring(0, position);
            uri = uri.replaceAll("\\\\", "/");
            uri = uri.replaceAll("%5c", "/");
            uri = uri.replaceAll("%2f", "/");
            
            encodeCharacter(SRCMSConstant.URIEXCLUDESTR, buff, uri);
            if (-1 != position)
            {
                String paramters = urlStr.substring(uri.length());
                encodeCharacter(SRCMSConstant.PARAMETEREXCLUDESTR, buff, paramters);
            }
            encodedUrl = buff.toString().replaceAll("\\+", "%20");
        }
        catch (IOException e)
        {
            LOGGER.error("Url encode failed, message:" + e.getMessage());
        }
        
        return encodedUrl;
    }
    
    private static void encodeCharacter(final String ExcludeStr, StringBuffer buff, String uri)
            throws UnsupportedEncodingException
    {
        for (int i = 0; i < uri.length(); ++i)
        {
            char c = uri.charAt(i);
            String str = String.valueOf(c);
            if (-1 != ExcludeStr.indexOf(str))
            {
                buff.append(str);
                continue;
            }
            
            buff.append(URLEncoder.encode(str, "UTF-8"));
        }
    }
    
    /**
     * 刪除文件
     * @param targetDirectory 目標目錄
     * @param targetFileName 目標文件名
     */
    public static void deleteExcelFile(String targetDirectory, String targetFileName)
    {
        try
        {
            File file = new File(targetDirectory);
            File[] files = null;
            if (file.exists() && file.isDirectory())
            {
                files = file.listFiles();
            }
            
            if (null != files && files.length > 0)
            {
                for (File tempFile : files)
                {
                    if (!tempFile.getName().equals(targetFileName))
                    {
                        org.apache.commons.io.FileUtils.forceDelete(tempFile);
                    }
                }
            }
            
            // 刪除掉空目錄
            if (file.exists())
            {
                files = file.listFiles();
                if (null != files && files.length == 0)
                {
                    org.apache.commons.io.FileUtils.forceDelete(file);
                }
            }
        }
        catch (Throwable e)
        {
            LOGGER.error("Delete file failed, message:" + e.getMessage());
        }
    }
    
    /**
     * 文件轉移
     *
     * @param srcFile
     * @param destFile
     * @throws SRCMSException 
     *
     */
    public static void transferTo(File srcFile, File destFile) throws SRCMSException
    {
        if (destFile.exists())
        {
            boolean ok = destFile.delete();
            if (!ok)
            {
                throw new SRCMSException("Delete dest file failed.");
            }
        }
        
        if (!srcFile.renameTo(destFile))
        {
            LOGGER.warn("Source file rename to dest file failed.");
            
            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            
            try
            {
                in = new BufferedInputStream(new FileInputStream(srcFile));
                out = new BufferedOutputStream(new FileOutputStream(destFile));
                IOUtils.copy(in, out);
            }
            catch (FileNotFoundException e)
            {
                throw new SRCMSException("Source file not found.", e);
            }
            catch (IOException e)
            {
                throw new SRCMSException("Source file write to dest file failed.", e);
            }
            finally
            {
                com.huawei.srcms.common.util.IOUtils.closeQuietly(in);
                com.huawei.srcms.common.util.IOUtils.closeQuietly(out);
            }
        }
    }
    
    public static byte[] getBytesFromFile(File file) throws IOException {
        //file size
        long length = file.length();
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        if (length > Integer.MAX_VALUE) {
             throw new IOException("File is to large " + file.getName());
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
             offset += numRead;
        }
         if (offset < bytes.length) {
                 throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        return bytes;


  }


 /**

* 將二進制的byte轉成string

*/

  public static  String  getStringFromByte(byte[] bytes){

String sTemp = new String(fileBlob, "GBK");
        String str = new String(sTemp.getBytes("UTF-8"), "UTF-8");


 }


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