文件拷贝与剪切工具类

package com.study.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/*
 * 文件操作工具类
 */
public class FileUtils {
    /*
     * 作用:将一个文件拷贝到另一个文件中
     * source: 文件源地路径+文件名
     * destination:文件目的地路径+文件名  会自动创建不存在的 文件目的地路径
     * type:false:覆盖destination中原有的内容 true:追加到destination中原有的内容的尾部
     * sourceDelete:原文件是否删除
     */
	public static Boolean copy(String source,String destination,Boolean type,Boolean sourceDelete) {
    	 Boolean result=true;
		 //1.数据源:读
		 File file = new File(source);
		 //数据源:写
		 File file1 = new File(destination);
		 //2.输入流 
		 InputStream is=null;
		 OutputStream os=null;
		 try {
			is=new BufferedInputStream(new FileInputStream(file));
		 //3.输入操作
		int len=-1;
		byte[] flush = new byte[1024];
		//创建不存在的 目的地
		if(!file1.exists()) {
	 	   //截取文件夹
			if(destination.contains("/")) {
			String path =destination.substring(0, destination.lastIndexOf("/"));
	   	    File file2 = new File(path);
	   	    file2.mkdirs();
			}
		} 
		//输出流
		os =new BufferedOutputStream(new FileOutputStream(file1,type)); //true:在文件中追加内容 默认false:覆盖
		while((len=is.read(flush))!=-1) {
			 String a = new String(flush, 0, len);
			os.write(flush, 0, len);
		}
		   os.flush();
		   
		 } catch (Exception e) {
				e.printStackTrace();
				result=false;
			}finally {
				//先打开后关闭
			   close(is,os);
			   if(sourceDelete && result) {
					//删除原文件
				   file.delete();
					 
				   }
			}
		 return result;
	}
	
	/*
	 * 关闭资源
	 */
	public static void close(Closeable...closeables) {
		   for (Closeable closeable : closeables) {
			if(closeable!=null) {
				try {
					closeable.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
	    Boolean rt = FileUtils.copy("a/b/a.txt", "a.txt", false,false);	
	    System.out.println(rt); 
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值