java使用io流对文件夹进行操作,实现对文件和文件夹的复制:
思路:
首先需要判断是文件还是文件夹,其次还需要判断源文件夹是否存在,其他的实现就比较简单了
package Ray.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestCopyDir2 {
public static void main(String[] args) {
//copy("E:/A","E:/C");
copyDir("E:/A","E:/C");
}
public static void copyDir(String srcFile,String dstFile) {
File srcfile = new File(srcFile);
if(!srcfile.exists()){
System.out.println("no exists");
return ;
}
File dstfile = new File(dstFile);
if(!dstfile.exists()){
dstfile.mkdir();
}
File[] list = srcfile.listFiles();
for(File file:list){
if(file.isFile()){
copy(srcFile+"/"+file.getName(), dstFile+"/"+file.getName());
}
if(file.isDirectory()){
copyDir(srcFile+"/"+file.getName(), dstFile+"/"+file.getName());
}
}
}
public static void copy(String src,String dst){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(new File(src)));
bos = new BufferedOutputStream(new FileOutputStream(new File(dst)));
byte[] b =new byte[1024];
int n = 0;
while((n =bis.read(b))!=-1){
bos.write(b, 0, n);
// bis.read();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}