開發工具類-簡單檔案操作相關

weixin_34041003發表於2013-09-14

與檔案簡單操作相關的一個工具類

package org.dennisit.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;


/**
 * Description: Simple File Handler Util , This Util rely on class<code>Logger</code> in package porg.apache.log4j.
 *
 * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-5 
 *
 * com.parser.util.FileUtil.java
 * 
 */

public class FileUtil {
    
    public static final Logger log = Logger.getLogger(FileUtil.class);

    
    /**
     * 
     * 建立檔案,如果檔案所在的目錄不存在,就建立目錄,然後床架檔案
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午09:46:29
     *                
     * @param fileName    待建立的檔名
     * @return            檔案是否建立成功
     */
    public static boolean createFile(String fileName){
        File file = new File(fileName);
        //判斷目錄是否存在
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //判斷檔案是否存在
        if(file.exists()){
            return true;
        }
        try{
            if(file.createNewFile()){
                return true;
            }else{
                return false;
            }
        }catch(Exception e){
            log.info("[File Create  Error]",e);
            return false;
        }
    }
    
    /**
     * 根據串值物件,建立檔案才
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午09:48:51
     *                
     * @param fileName    
     *                         檔名
     * @param str        
     *                         要寫入的檔案內容
     * @param append    
     *                         <dl>檔案寫入的方式,追加還是替換
     *                             <dd>true值表示在原來內容的基礎上記性內容追加</dd>
     *                             <dd>false值表示清空原來內容,重新寫入</dd>
     *                         </dl>
     * @return
     */
    public static boolean createFile(String fileName,String str,boolean append){
        boolean ret = false;
        try{
            if(createFile(fileName)){
                FileOutputStream  fileOutputStream = new FileOutputStream(fileName,append);
                fileOutputStream.write(str.getBytes());
                fileOutputStream.close();
                ret = true;
            }
        }catch (Exception e){
            log.info("[File Write Error]\t" + str, e );
            ret = false;
        }
        
        return ret;
    }
    
    /**
     * 
     * 根據流建立檔案
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午09:53:00
     *                
     * @param fileName
     *                         檔名稱
     * @param inputStream
     *                         輸入流
     * @param append        <dl>檔案寫入的方式,追加還是替換
     *                             <dd>true值表示在原來內容的基礎上記性內容追加</dd>
     *                             <dd>false值表示清空原來內容,重新寫入</dd>
     *                         </dl>
     * @return
     */
    public static boolean createFile(String fileName, InputStream inputStream,boolean append){
        boolean ret = false;
        try{
            if(createFile(fileName)){
                FileOutputStream  fileOutputStream = new FileOutputStream(fileName,append);
                byte[] buffer = new byte[4096];
                int n_bytes;
                while ( (n_bytes = inputStream.read(buffer)) != -1 ) {
                    fileOutputStream.write(buffer, 0, n_bytes);
                    fileOutputStream.flush();
                }                
                fileOutputStream.close();
                ret = true;
            }
        }catch (Exception e){
            log.info("檔案寫入失敗:" + fileName, e );
            ret = false;
        }
        
        return ret;
    }
    

    /**
     * 
     * 根據檔案路徑獲取路徑下的檔名
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午09:54:35
     *                
     * @param path
     * @return                返回資料夾/檔名的list集合,只是檔名,不包含路徑
     * @throws Exception
     */
    public static List<String> fileNameList(String path) throws Exception{
        List<String> list =  new ArrayList<String>();
        File file = new File(path);
        if( file == null || !file.exists() ) 
            throw new Exception("File (" + path + ") is not Found");
        for ( File f : file.listFiles() ) 
            list.add(f.getName());
        return list;
    }
    
    
    
    /**
     * 
     * 複製檔案功能
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午10:08:17
     *                
     * @param originalFileName
     *                             原始檔案路徑
     * @param destinationFileName
     *                             目標檔案路徑
     * @return
     */
    public static boolean copyFile(String originalFileName,String destinationFileName){
        boolean ret = true;
        if(originalFileName == null || destinationFileName == null){
            ret = false;
        }
        try{
            File sourceFile = new File(originalFileName);
            File destinationFile = new File(destinationFileName);
            
            //判斷原始檔是否存在
            if(!sourceFile.exists()){
                log.info("Original File (" + originalFileName + ") Nod Found ." );
                return false;
            }
            
            //建立目標檔案
            if(!createFile(destinationFileName)){
                log.info("Target File (" + destinationFileName +") Create Error ." );
                return false;
            }
            
            if(copySingleFile(sourceFile, destinationFile)){                
                log.info("Copy File (" + originalFileName + ") to ("  + destinationFileName +")");
            }else{
                ret = false;
                log.info("Copy File (" + originalFileName + ") to ("  + destinationFileName +") ERROR ");            
            }
        }catch (Exception e){
            log.info("Copy File ERROR ! File Name is : " + originalFileName, e );
            ret = false;
        }
        return ret;
    }
    
    
    /**
     * 
     * 複製檔案的實際處理類
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午10:08:17
     *                
     * @param sourceFileName
     *                             檔案原來名稱
     * @param destinationFileName
     *                             目標檔名稱
     * @return
     */
    private static boolean copySingleFile(File sourceFile,File destinationFile){
        boolean copyFlg = false;
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        DataOutputStream dataOutputStream = null;
        try{
            fileInputStream = new FileInputStream(sourceFile);
            dataInputStream = new DataInputStream(new BufferedInputStream(fileInputStream));
            fileOutputStream = new FileOutputStream(destinationFile);
            dataOutputStream = new DataOutputStream(new BufferedOutputStream(fileOutputStream));
            byte[] b = new byte[1024];
            int len;
            while((len = dataInputStream.read(b)) != -1){
                dataOutputStream.write(b,0,len);
            }
            
            dataOutputStream.flush();
        }catch(Exception e){
            log.info("File Copy ERROR",e);
        }finally{
            try{
                if(dataInputStream != null){
                    dataInputStream.close();
                }
                if(dataOutputStream != null){
                    dataOutputStream.close();
                }
            }catch (Exception e){
                
            }
        }
        //判斷檔案大小是否相同
        if(sourceFile.length() == destinationFile.length()){
            copyFlg = true;
        }
        
        return copyFlg;
    }
    

    
    /**
     * 刪除檔案
     *
     * @author <a href='mailto:dennisit@163.com'>Cn.蘇若年(En.dennisit)</a> Copy Right since 2013-9-14 上午10:10:22
     *                
     * @param fileName
     * @return
     */
    public boolean deleteFile(String fileName){
        File file = new File(fileName);
        if(!file.exists()){
            log.info("Delete File Not Found :" + fileName );
            return false;
        }
        try{
            file.delete();
        }catch(Exception e){
            log.info("Delete File Error",e);
            return false;
        }
        return true;
    }
    
    
    public static void main(String[] args) throws Exception {
        copyFile("F:/BaiDu Yum/蘇若年-HtmlParser篇Filter應用說明.pdf", "D:/test.pdf");
        createFile("F:/tmp/test.txt");
        createFile("F:/tmp/test.txt","simple File Util", true);
    }
}

 

相關文章