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