//文件拷贝---------------------------------------------------------------------------- public void copyFile(File src_, File dest_) { File src = src_;//源文件 File destination = dest_;//目的地 if(!src.isFile()) { new Exception("ssssssss"); } InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); os = new FileOutputStream(destination,true);//true是可以继续写,flase则覆盖 byte[] flush = new byte[1024]; int len; while(-1!=(len=is.read(flush))) { os.write(flush, 0, flush.length); } os.flush();//记得手动flush一下 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(null!=os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(null!=is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } //文件夹拷贝------------------------------------------------------------- public class DirCopy { public static void main(String[] args) { String srcPath = "d:/javac/bb"; String destPath = "d:/javac/aa"; File src = new File(srcPath); File dest = new File(destPath); if(src.isDirectory()) { dest = new File(destPath, src.getName()); } copyDirDetil(src,dest); } private static void copyDirDetil(File src, File dest) { if(src.isFile()) { FileCopy fc = new FileCopy(); fc.copyFile(src, dest); } else if(src.isDirectory()) { dest.mkdirs(); for(File temp : src.listFiles()) { copyDirDetil(temp, new File(dest, temp.getName())); } } } }
时间: 2024-11-14 06:23:08