源码:
package com.IO.Input_OutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileCopy {
// 文件夹的拷贝:使用文件字节的输入和输出流实现
public static void main(String[] args) {
Copy(new File("d:/aaTest"), new File("d:/aaCopyTest"));
}
// 封装到一个方法中:
public static void Copy(File srcPath, File destPath) {
destPath.mkdirs();// 目的文件夹的创建(因为一开始并不存在该文件夹,因此需要先创建)
// 选择流:两种都要选择使用
InputStream is = null;
FileOutputStream os = null;
try {
if (null != srcPath && srcPath.exists()) {// 判断:源文件夹存在且不为空
File[] files = srcPath.listFiles();// 将每一个文件找到并放到文件数组files中
if (files != null) {// 能找到则进行下面操作:
for (File s : files) {// 遍历每一个文件/文件夹
if (s.isFile()) {// 是文件,则直接拷贝
// 操作:分段读取
is = new FileInputStream(s);
os = new FileOutputStream(destPath.getAbsolutePath() + "/" + s.getName());
byte[] flush = new byte[1024];// 缓冲容器,这里是每1024个字节(1kb)读一次。
// 解释:分段读取到的字符放到len中,作为接收长度
int len = -1;// 接收长度
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);// 分段写入
os.flush();// 刷新
}
} else {// 不是文件,是文件夹则调用自己:
// 使用递归思想(重复调用):
Copy(s, new File(destPath.getAbsolutePath() + "/" + s.getName()));
}
}
}
}
} 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();// 先关闭os
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (is != null) {
is.close();// 再关闭先打开的is
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}