拷贝目录:
将D:\course拷贝到C盘根下....需要使用到:
FileInputStream
FileOutputStream
File
可能需要使用到递归。你尝试实现一下!
思路:
拷贝方法:传入要拷贝路径,拷贝到的路径
判断拷贝路径是否存在遍历,获取每个文件的文件名,文件路径
if 判断该file 为文件 还是文件夹
else 文件夹 递归调用 拷贝方法else 文件 调用拷贝方法
可用内部类实现?
拷贝复制方法,传入参数 文件路径,拷贝到的文件路径(拷贝到的路径+文件名?)
调用
FileInputStream,read(byte[] b)方法 读\输入到内存
调用
FileOutputStream,write(byte[] b,0 ,readCount)方法 写\输出,建立文件
- 代码实现
public class copy {
public static void main(String[] args) {
//src指源文件,是source的缩写; dest指目标,是destination的缩写
new copy().copyMethod("E:\\JavaSE\\IOfile","E:\\JavaSE\\test\\11\\");
//也可将路径创建为File对象,传参改为File
}
//拷贝方法 参数为拷贝目录路径,要拷贝到的路径
public void copyMethod(String srcPath,String destPath){
//判断目标拷贝目录是否存在,创建目标目录
new File(destPath).mkdirs();
//创建File对象,获取获取当前对象目录下所有的子文件。
File[] files = (new File(srcPath)).listFiles();
for(File f : files){ //foreach遍历
//如果File为目录
if(f.isDirectory()){
String filePath = f.getAbsolutePath(); //获取目录路径、名称
String fileName = f.getName();
(new File(destPath+"\\"+fileName)).mkdir(); //在拷贝位置创建目录,拷贝位置+File名称
copyMethod(filePath,(destPath+"\\"+fileName)); //递归调用,传入当前目录路径、拷贝路径+File名称,拷贝子目录文件
//如果File为文件
}else if(f.isFile()){
String filePath = f.getAbsolutePath();
String fileName = f.getName();
//拷贝方法,传入文件路径,拷贝到的文件路径(拷贝到的路径+文件名?)
copy(filePath,(destPath+"\\"+fileName));
}
}
}
public void copy(String path,String copyPath){
//定义字节输入、输出流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(path);
fos = new FileOutputStream(copyPath);
//一边读一边写
byte[] bytes = new byte[1024*512];
int readCount = 0;
while ((readCount = fis.read(bytes))!= -1){
fos.write(bytes,0,readCount);
}
//刷新流
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//关闭流
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}