关于文件/文件夹通用复制程序实例,在此程序中,只要将目标文件和源文件都放入到demo中,便可以实现完整复制,支持文件与文件夹复制
注释已经写在代码中~~
package Demo8FileCopy;
import java.io.File;
public class Demo8 {
public static void main(String[] args) {
//源文件路径
String src = "E:/";
//目标路径路径
String dest = "D:/";
//拷贝的文件或文件夹名
String name = "dd";
//原文件的File对象
File srcFile = new File(src,name);
//拷贝文件的File对象
File destFile = new File(dest);
//拷贝
copy(srcFile,destFile);
}
public static void copy(File src, File dest){
if(src.isFile()){
FileUtil.copy(src, new File(dest,src.getName()));
}else if(src.isDirectory()){
//FileUtil.copy(src, new File(dest.getAbsolutePath(),src.getName()));
File newFile = new File(dest.getAbsolutePath(),src.getName());
newFile.mkdirs();
for(File temp : src.listFiles()){
//递归复制文件夹中的子目录
copy(temp,newFile);
}
}
}
}
package Demo8FileCopy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
public static void copy(File src , File dest){
//1、建立关联
//2、选择流
InputStream is = null;
OutputStream os =null;
try {
is = new FileInputStream(src.getAbsolutePath());
os = new FileOutputStream(dest.getAbsolutePath());
//3、选择运输的数组
byte[] data = new byte[1024];
int len = 0;
while((len=is.read(data))!=-1){
//把data写入输出文件中
os.write(data, 0, len);
}
//强制输出
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(os!=null){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
|