package com.hiredmyway.action.test;
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 TestCopy_File_folder {
/**
* 递归方法 (实现文件夹拷贝到另一个文件夹下)
* @param source
* @param target
*/
public static void copy(File source, File target) {
File tarpath = new File(target, source.getName());
if (source.isDirectory()) {
tarpath.mkdir();
File[] dir = source.listFiles();
for (int i = 0; i < dir.length; i++) {
copy(dir[i], tarpath);
}
} else {
try {
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(tarpath);
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
//is.close();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
// 把"test11"文件夹包括里面的文件一起拷贝到D:\\盘的根目录下。
copy(new File("C:\\test11"), new File("D:\\"));
System.out.println("read write success!");
}
}
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 TestCopy_File_folder {
/**
* 递归方法 (实现文件夹拷贝到另一个文件夹下)
* @param source
* @param target
*/
public static void copy(File source, File target) {
File tarpath = new File(target, source.getName());
if (source.isDirectory()) {
tarpath.mkdir();
File[] dir = source.listFiles();
for (int i = 0; i < dir.length; i++) {
copy(dir[i], tarpath);
}
} else {
try {
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(tarpath);
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
//is.close();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
// 把"test11"文件夹包括里面的文件一起拷贝到D:\\盘的根目录下。
copy(new File("C:\\test11"), new File("D:\\"));
System.out.println("read write success!");
}
}