62,615
社区成员
发帖
与我相关
我的任务
分享
package IO;
/**
* 文件夹拷贝
*/
import java.io.File;
public class File08 {
public static void main(String[] args) {
String srcpath ="e:/program/study";
String destpath="e:/program/dir";
try {
util.copyFileDire(srcpath,destpath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class util {
//文件路径
public static void copyFile(String srcpath,String destpath) throws Exception{
File src = new File(srcpath);
File dest = new File(destpath);
copyFile(src, dest);
}
//文件对象
public static void copyFile(File src,File dest) throws Exception{
if(!src.isFile()){
System.out.println("不是文件!");
throw new Exception("操作错误");
}
if(!dest.exists()){
dest.createNewFile();
}
InputStream in = new FileInputStream(src);
OutputStream out =new FileOutputStream(dest);
byte [] buf = new byte[1024];
int len =0;
while(-1!=(len=in.read(buf))){
out.write(buf, 0, len);
out.flush();
}
}
//文件夹拷贝
public static void copyFileDire(String srcpath,String destpath){
File src =new File(srcpath);
File dest =null;
if(src.isDirectory()){
dest= new File(destpath,src.getName());
}
copyFiledetail(src,dest);
}
public static void copyFiledetail(File src,File dest){
if(src.isFile()){
try {
util.copyFile(src, dest);
} catch (Exception e) {
e.printStackTrace();
}
}else if(src.isDirectory()){
dest.mkdirs();
for(File temp:src.listFiles()){
copyFiledetail(temp,new File(dest,temp.getName()));
}
}
}
}
if (src.isDirectory()) {
dest = new File(destpath, src.getName());
}
copyFiledetail(src, dest);
这里如果不是文件夹的话还是会调用copyFiledtail方法,这个时候dest为null,所以就报了空指针异常else if(src.isFile()){
try {
dest= new File(destpath);
copyFile(src, dest);
} catch (Exception e) {
System.out.println("sdsd'");
e.printStackTrace();
}
懂了、我加了这段代码 ,文件夹和文件都能拷贝了现在