package holiday.day09;
import java.io.File;
/**
* 递归实现文件夹Copy
*/
public class FolderCopy {
public static void main(String[] args) {
copyFolder("D:/图片","F:/File");
}
public static void copyFolder(String originalPath, String ectyPath){ //源文件路径、目标路径
File original = new File(originalPath);
deep(original,ectyPath);
}
public static void deep(File src, String ectype){
if (src==null || !src.exists()){
return;
}else if(src.isDirectory()){
String namepath = ectype+"/"+src.getName();
File dest = new File(namepath);
boolean flag = dest.mkdirs();
for(File temp:src.listFiles()){
deep(temp, namepath);
}
}else{
FileCopy.copy(src.getAbsolutePath(),ectype+"/"+src.getName());
}
}
public static void copy(String srcPath, String destPath){
File src = new File(srcPath);
File dest = new File(destPath);
InputStream is = null;
OutputStream os = null;
//int temp;
try {
is = new BufferedInputStream(new FileInputStream(src)); //操作(分段读取)
os = new BufferedOutputStream(new FileOutputStream(dest));
int len=-1;
byte[] flush = new byte[1024];
while((len=is.read(flush))!=-1){
os.write(flush,0,len);
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally {
if(null!=os){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件字节流可以处理所有的文件,但是字节流不能很好的处理Unicode字符,经常会出现“乱码”现象。所以,我们处理文本文件,一般可以使用文件字符流,它以字符为单位进行操作。