Java IO中的文件複製實例(原創)

package org.jack.tools.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.util.logging.Logger;

public class FileCopyUtils {
	
	private static Logger logger = Logger.getLogger(FileCopyUtils.class.getName());  
	
	public static void main(String[] args) throws IOException {		
		//源文件夾
        String srcDir = "D:/user/test/";
         //目標文件夾
        String destDir = "D:/user/testcopy/";
        //創建目標文件夾
        createDirectory(destDir);
		//判斷源文件夾裏面是否有文件
        File srcFiles = null;
		try {
			srcFiles = new File(srcDir);
		} catch (Exception e) {
			e.printStackTrace();
		}
        File[] files = srcFiles.listFiles();
        if (files.length == 0) {
			throw new IOException("源文件夾[" + srcDir + "]中沒有文件!");
		}
        for (File file : files) {
			if (file.isFile()) {
				//將源文件夾中所有文件複製到目標文件夾中
				//FileUtils.copyFile(file, new File(destDir + file.getName()));
				//將源文件夾中後綴名爲pdf的文件複製到目標文件夾中
				//FileUtils.copyFile(file, new File(destDir + file.getName()),"pdf");
				readFile(file.getAbsolutePath(), "GBK");
			}
		}
        //FileUtils.copyDirectiory("D:/user/test/src", "D:/aaaaa/testcopy/");
	}

	//複製文件到指定的目錄下
	public static void copyFile(File srcFile, File destFile) throws IOException{
		BufferedInputStream buffin = null;
		BufferedOutputStream buffout = null;
		try {
			buffin = new BufferedInputStream(new FileInputStream(srcFile));
			buffout = new BufferedOutputStream(new FileOutputStream(destFile));
			
			byte[] b = new byte[1024*5];
			int len=0;
			while((len = buffin.read(b)) != -1){
				buffout.write(b,0,len);
			}
			logger.info("文件[" + srcFile.getName() + "]已被成功拷貝到目錄[" 
					+ destFile.getPath().substring(0,destFile.getPath().lastIndexOf(File.separator)) + "]下。");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(buffin != null){
					buffin.close();
				}
				if (buffout != null) {
					buffout.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	//複製指定格式的文件到指定的目錄下
	public static void copyFile(File srcFile, File destFile, String ext) throws IOException{
		String exten = ext;
		String srcExt = srcFile.getName().substring(srcFile.getName().lastIndexOf(".") + 1);
		
		if(!exten.equals(srcExt)){
			logger.info("文件["+ srcFile.getName() +"]不是[" + ext + "]格式!");
		}else{
			BufferedInputStream buffin = null;
			BufferedOutputStream buffout = null;
			try {
				buffin = new BufferedInputStream(new FileInputStream(srcFile));
				buffout = new BufferedOutputStream(new FileOutputStream(destFile));
				
				byte[] b = new byte[1024*5];//定義5kb大小的緩衝區
				int len = 0;// 每次讀取的字節長度
				while((len = buffin.read(b)) != -1){
					buffout.write(b,0,len);// 將讀取的內容,寫入到輸出流當中 
				}
				logger.info("文件[" + srcFile.getName() + "]已被成功拷貝到目錄[" + 
						destFile.getPath().substring(0,destFile.getPath().lastIndexOf(File.separator)) + "]下。");
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if(buffin != null){
						buffin.close();
					}
					if (buffout != null) {
						buffout.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
		
	}
	
	//創建文件夾
	public static void createDirectory(String dirPath){
        try {
			File fileDir = new File(dirPath);
			if(!fileDir.exists() && !fileDir.isDirectory()){
				fileDir.mkdir();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//複製文件夾
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
         // 新建目標目錄
        (new File(targetDir)).mkdirs();
         // 獲取源文件夾當前下的文件或目錄
        File[] file = (new File(sourceDir)).listFiles();
         for (int i = 0; i < file.length; i++) {
             if (file[i].isFile()) {
                 // 源文件
                File sourceFile = file[i];
                 // 目標文件
                File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                 copyFile(sourceFile, targetFile);
             }
             if (file[i].isDirectory()) {
                 // 準備複製的源文件夾
                String dir1 = sourceDir + "/" + file[i].getName();
                 // 準備複製的目標文件夾
                String dir2 = targetDir + "/" + file[i].getName();
                 copyDirectiory(dir1, dir2);
             }
         }
     }

    /**
     * 
     * @param srcFileName
     * @param destFileName
     * @param srcCoding
     * @param destCoding
     * @throws IOException
     */
    public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// 把文件轉換爲GBK文件
       BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
            char[] cbuf = new char[1024 * 5];
            int len = cbuf.length;
            int off = 0;
            int ret = 0;
            while ((ret = br.read(cbuf, off, len)) > 0) {
                off += ret;
                len -= ret;
            }
            bw.write(cbuf, 0, off);
            bw.flush();
        } finally {
            if (br != null)
                br.close();
            if (bw != null)
                bw.close();
        }
    }
    
    /**
     * 讀取文件中內容
    * 
     * @param path
     * @return
     * @throws IOException
     */
    public static String readFileToString(String path) throws IOException {
        String resultStr = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            byte[] inBuf = new byte[2000];
            int len = inBuf.length;
            int off = 0;
            int ret = 0;
            while ((ret = fis.read(inBuf, off, len)) > 0) {
                off += ret;
                len -= ret;
            }
            resultStr = new String(new String(inBuf, 0, off, "GBK").getBytes());
        } finally {
            if (fis != null)
                fis.close();
        }
        return resultStr;
    }
    
    /**
     * 使用文件通道的方式FileChannel複製文件,效率比Buffered拷貝效率高三分之一以上
     * 
     * @param src 源文件
     * @param target 目標文件
     */
     public void fileChannelCopy(File src, File target) {
         FileInputStream fi = null;
         FileOutputStream fo = null;
         FileChannel in = null;
         FileChannel out = null;
         try {
             fi = new FileInputStream(src);
             fo = new FileOutputStream(target);
             in = fi.getChannel();//得到對應的文件通道
             out = fo.getChannel();//得到對應的文件通道
             in.transferTo(0, in.size(), out);//連接兩個通道,並且從in通道讀取,然後寫入out通道
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             try {
                 fi.close();
                 in.close();
                 fo.close();
                 out.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     
      /**
      * 
      * @param filepath
      * @throws IOException
      */
     public static void deleteFile(String filepath) throws IOException {
         File f = new File(filepath);// 定義文件路徑
         if (f.exists() && f.isDirectory()) {// 判斷是文件還是目錄
             if (f.listFiles().length == 0) {// 若目錄下沒有文件則直接刪除
                 f.delete();
             } else {// 若有則把文件放進數組,並判斷是否有下級目錄
                 File delFile[] = f.listFiles();
                 int i = f.listFiles().length;
                 for (int j = 0; j < i; j++) {
                     if (delFile[j].isDirectory()) {
                    	 deleteFile(delFile[j].getAbsolutePath());// 遞歸調用del方法並取得子目錄路徑
                     }
                     delFile[j].delete();// 刪除文件
                 }
             }
         }
     }
     
     /**
      * 功能:Java讀取txt文件的內容
      * 步驟:
 	  * 1:先獲得文件句柄
      * 2:獲得文件句柄當做是輸入一個字節碼流,需要對這個輸入流進行讀取
      * 3:讀取到輸入流後,需要讀取生成字節流
      * 4:一行一行的輸出。readline()。
      * @param filePath 文件完整路徑
 	  * @param encoding 文件編碼格式,默認傳入GBK
      */
     public static void readFile(String filePath, String encoding){
    	 String ext = filePath.substring(filePath.lastIndexOf(".") + 1);
    	 if (!ext.trim().equalsIgnoreCase("txt")) {
			logger.info("文件[" + filePath + "]不是TXT格式!目前只支持讀取TXT格式的文本文件!");
		}else{
			try {
	             File file = new File(filePath);
	             if(file.isFile() && file.exists()){ //判斷文件是否存在
	                 InputStreamReader read = new InputStreamReader(
	                 new FileInputStream(file),encoding);//考慮到編碼格式
	                 BufferedReader bufferedReader = new BufferedReader(read);
	                 String lineTxt = null;
	                 System.out.println("*******************************************************************");
	                 while((lineTxt = bufferedReader.readLine()) != null){
	                	 System.out.println(lineTxt);
	                	 //這裏可以寫別的代碼,處理其他邏輯
	                 }
	                 System.out.println("*******************************************************************");
	                 read.close();
		     }else{
		    	 logger.info("找不到指定的文件!");
		     }
		     } catch (Exception e) {
		    	 logger.info("讀取文件內容出錯!");
		         e.printStackTrace();
		     }
		}
     }
}


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