JAVASE_File类(实践)——目录拷贝
生活随笔
收集整理的這篇文章主要介紹了
JAVASE_File类(实践)——目录拷贝
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 實現代碼
- 實現截圖
- 執行前截圖
- 執行后截圖
實現代碼
package Filecopy01;import java.io.*;/* * 拷貝源 * * */ public class CopyAll {public static void main(String[] args) {//拷貝源File srcFile=new File("G:\\植物大戰僵尸年度英文版");//拷貝目標File destFile=new File("E:\\");//調用拷貝方法copyDir(srcFile,destFile);}private static void copyDir(File srcFile,File destFile){if(srcFile.isFile()){FileInputStream in=null;FileOutputStream out=null;try {//讀這個文件in=new FileInputStream(srcFile);//寫到這個文件中String destDir=(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")+srcFile.getAbsolutePath().substring(3);out=new FileOutputStream(destDir);//一邊讀一邊寫byte[]bytes=new byte[1024*1024];int readCount=0;while((readCount=in.read(bytes))!=-1){out.write(bytes,0,readCount);}out.flush();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}}}//如果是一個文件的話,遞歸結束return;}File []files=srcFile.listFiles();for(File file:files){if(file.isDirectory()){String srcDir=file.getAbsolutePath();String destDir=(destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\")+srcDir.substring(3);File newFile=new File(destDir);if(!newFile.exists()){newFile.mkdirs();}}//遞歸調用copyDir(file,destFile);}} }實現截圖
執行前截圖
執行后截圖
總結
以上是生活随笔為你收集整理的JAVASE_File类(实践)——目录拷贝的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVASE——File类
- 下一篇: 正则表达式实际操作