黑马程序员技术交流社区
标题:
复制文件夹的程序报错!
[打印本页]
作者:
Aimer_WJY
时间:
2014-4-1 13:41
标题:
复制文件夹的程序报错!
public class CopyFile {
public static void main(String [] args) throws Exception{
File src=new File("F:\\test2");
System.out.println(src.getAbsolutePath());
File des=new File("F:\\copy_test2");
File[] arr=src.listFiles();
for(File a:arr){
if(a.isDirectory())
copyDirectory(a,src,des);
else
copyFile(a,src,des);
}
}
public static void copyFile(File a,File src,File des) throws Exception{
//BufferedInputStream buis=new BufferedInputStream(new FileInputStream(src.getAbsolutePath()));
FileInputStream fis=new FileInputStream(a.getAbsolutePath());
//BufferedOutputStream buos=new BufferedOutputStream(new FileOutputStream(des.getAbsolutePath()));
FileOutputStream fos=new FileOutputStream(a.getAbsolutePath());
int len=0;
while((len=fis.read())!=-1){
fos.write(len);
}
}
public static void copyDirectory(File f,File src,File des) throws Exception{
File name=new File(f.getAbsolutePath(),f.getName());
name.mkdir();
File[] arr=src.listFiles();
for(File a:arr){
if(a.isFile()){
copyFile(a,src,des);
}
else{
copyDirectory(a,src,des);
}
}
}
}
复制代码
错误是:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.ref.Finalizer.<init>(Finalizer.java:85)
at java.lang.ref.Finalizer.register(Finalizer.java:90)
目前功能也没用实现,请大神指导下~
作者:
osully
时间:
2014-4-1 13:51
看下我之前写的吧
个人觉得还不错
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyDemo2 {
public static void main(String[] args) throws IOException {
File source = new File("D:\\myjava\\myself\\新建文件夹");
File target = new File("D:\\myjava\\test", source.getName());
if(source.isDirectory())
folderCopy(source, target);
else
fileCopy(source, target);
}
public static void folderCopy(File source, File target) throws IOException {
if (!target.exists()) {
target.mkdir();
}
File[] files = source.listFiles();
for (File file : files) {
String newSource = file.getAbsolutePath();
String newtarget = newSource.replace(source.getAbsolutePath(),
target.getAbsolutePath());
File newFile = new File(newtarget);
if (file.isDirectory()) {
folderCopy(file, newFile);
}
else {
fileCopy(file, newFile);
}
}
}
public static void fileCopy(File file, File newFile) throws IOException {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(newFile);
BufferedInputStream bfis = new BufferedInputStream(fis);
BufferedOutputStream bfos = new BufferedOutputStream(fos);
int i = 0;
while ((i = bfis.read()) != -1) {
bfos.write(i);
}
bfis.close();
bfos.close();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2