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();
		     }
		}
     }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值