用java实现拷贝目录以及目录下文件
非静态方法的FileCopy(java.io.File文件, java.io.File文件)无法从静态上下文引用“”
获取源下面的子目录
File[] files = srcFile.listFiles();
- 新建目录要获取目录的绝对路径,再创建,用file.getAbsolutePath()获取路径,然后创建File对象,进行文件目录的创建。
- 文件拷贝的话是用FileOutputStream和FileInputStream,来拷贝。
用FileInputStream来读文件,然后很重要的一步就是确定FileOutputStream对象要输出的路径,就是文件准备拷贝到哪个地方,要把路径给确定下来。
- readCount=in.read(bytes)。in是FileInputStream对象,是要读取文件到bytes数组里,所以括号内一定要写bytes
- out.write(bytes,0,readCount); 真正开始写是out.write方法
- 最后,记得在递归结束条件里加return;!!!!!
package com.java.io;
import java.io.*;
public class CopyAll {
public static void main(String[] args) throws Exception{
File srcFile = new File("F:\\JavaSE相关文档与面试题");
File destFile = new File("D:\\");
FileCopy(srcFile,destFile);
}
public static void FileCopy(File srcFile,File destFile){
if (srcFile.isFile()){
//是文件的话,就要开始拷贝
FileInputStream in =null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
String path = ( destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcFile.getAbsolutePath().substring(3);
out = new FileOutputStream(path);
byte[] bytes = new byte[1024*1024];
int readCount = 0;
while ((readCount=in.read(bytes))!=-1){
out.write(bytes,0,readCount);
}
//刷新
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
File[] files =srcFile.listFiles();
for (File file :files){
// System.out.println(file);
if (file.isDirectory()){
//新建对应目录
//新建目录要获取目录的绝对路径,再创建
String srcDir = file.getAbsolutePath();
String destDir =( destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcDir.substring(3);
File newFile = new File(destDir);
if(!newFile.exists()){
newFile.mkdirs();
}
}
FileCopy(file,destFile);
//此目录下可能还有字目录,往里面深挖
}
}
}