代码分类之实现复制文件或文件夹

来源:互联网 发布:手机网络新游戏 编辑:程序博客网 时间:2024/06/10 14:45


拷贝一个文件的算法比较简单,当然,可以对它进行优化,比如使用缓冲流,提高读写数据的效率等。但是在复制文件夹时,则需要利用Flie类在目标文件夹中创建相应的目录,并且使用递归方法.

拷贝文件夹内容public static void copyfile(String inputpath, String outputpath) {// TODO Auto-generated method stubFile inputfile = new File(inputpath);File outputfile = new File(outputpath);if(!inputfile.isDirectory()) {File parentFile = outputfile.getParentFile();parentFile.mkdirs();CopyOneFile(inputpath, outputpath); //拷贝单一的文档}else{String[] nextfilename = inputfile.list();outputfile.mkdirs();for(String r : nextfilename){copyfile(inputpath + File.separator + r, outputpath + File.separator + r); //递归拷贝}}}public static void CopyOneFile(String inputpath, String outputpath) {BufferedInputStream inBuff = null;BufferedOutputStream outBuff = null;try {inBuff = new BufferedInputStream(new FileInputStream(inputpath));outBuff = new BufferedOutputStream(new FileOutputStream(outputpath));// 缓冲数组byte[] b = new byte[1024 * 5];int len;while ((len = inBuff.read(b)) != -1) {outBuff.write(b, 0, len);}outBuff.flush();} catch (Exception e) {e.printStackTrace();} finally {// 关闭流if (inBuff != null) {try {inBuff.close();} catch (Exception e) {e.printStackTrace();}}if (outBuff != null) {try {outBuff.close();} catch (Exception e) {e.printStackTrace();}}}}

0 0