video175 IO_文件拷贝—拓展:copy 文件夹及文件夹下内容到目标文件夹下
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;
/**
* copy 该文件夹及文件夹下内容到目标文件夹下
* @author lei.ai
*
*/
public class IOCopy03extend {
public static void main(String[] args) throws IOException {
copytodir("D:\\code\\Pro10\\test","D:\\code\\Pro10\\copytest");
}
private static void copytodir(String sourcepath,String destpath) throws IOException {
// TODO Auto-generated method stub
File sorce = new File(sourcepath); //源文件
File dest = new File(destpath);
//创建目标文件夹
dest.mkdirs(); //如果目标文件夹已存在,则创建失败
//将源文件名与目标路径相结合,存到buffd中
File buffd = new File(dest.getAbsolutePath(),sorce.getName());
if (sorce!=null && sorce.exists()) {
if (sorce.isFile()) { //如果是文件,在目标目录中创建该文件,并将内容复制
buffd.createNewFile();
copyfile(sorce.getAbsolutePath(), buffd.getAbsolutePath());
}else { //如果是文件夹,则递归调用
for(File s:sorce.listFiles()) {
File buffs = new File(sorce.getAbsolutePath(),s.getName());
copytodir(buffs.getAbsolutePath(),buffd.getAbsolutePath());
}
}
}
}
private static void copyfile(String sourcepath,String destpath) {
//1.创建源
File sorce = new File(sourcepath); //源文件
File dest = new File(destpath); //目标文件
//2.选择流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(sorce);
os = new FileOutputStream(dest);
//3.操作
//分段读取
byte[] flush = new byte[1024];
int len; //定义解码接收长度
while ((len=is.read(flush))!=-1) {
os.write(flush, 0, len);
/*
String st = new String(flush, 0, len); //编码
byte[] temp = st.getBytes(); //解码
os.write(temp, 0, temp.length); //写入
*/
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally { //4、释放资源 分别关闭 先打开的后关闭
if (os!=null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}