模擬copy命令,接收原始檔路徑和目標檔案路徑,實現檔案或資料夾拷貝操作
package learning;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import javax.xml.crypto.Data;
public class IOStreamPractice {
//模擬copy命令,接收原始檔路徑和目標檔案路徑,實現檔案或資料夾拷貝操作
//需求分析:各種檔案都有,用位元組流;大檔案的拷貝
//思路:採用部分拷貝,拷貝一部分就輸出一部分
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
String srcPath=sc.next();
String desPath=sc.next();
File srcFile=new File(srcPath);
File desFile=new File(desPath);
boolean b=FileUtil.copyImpl(srcFile,desFile);
System.out.println(b? "拷貝成功":"拷貝失敗,請排查原因");
}
}
class FileUtil {
public static boolean copyImpl(File srcFile,File desFile) throws Exception{
if(!srcFile.exists()) return false; //處理特殊情況
if(!desFile.getParentFile().exists()) desFile.getParentFile().mkdirs();
if(srcFile.isFile()) { //區分拷貝的是普通檔案,還是目錄檔案 return FileUtil.copyNormal(srcFile,desFile); } else { return FileUtil.copyDir(srcFile,srcFile,desFile); } } private static boolean copyNormal(File srcFile, File desFile) throws Exception{ //被copyDir呼叫時父目錄可能不存在 if(!desFile.getParentFile().exists()) desFile.getParentFile().mkdirs(); InputStream input=new FileInputStream(srcFile); OutputStream output=new FileOutputStream(desFile); byte[] buffer=new byte[1024]; //每趟最多拷貝1024位元組 int len=0; while( (len=input.read(buffer))!=-1 ) { //一直把檔案讀完為止 output.write(buffer,0,len); } return true; } private static boolean copyDir(File File,File srcFile, File desFile) throws Exception{ if(File.isDirectory()) { //是目錄,則遞迴拷貝 File[] subFiles=File.listFiles(); if(subFiles!=null) { for(int i=0;i<subFiles.length;i++) copyDir(subFiles[i], srcFile, desFile); } } else { //重新構建路徑名 String oldPath=File.getPath().replace(srcFile.getPath()+File.separator,""); File newFile=new File(desFile.getPath(), oldPath); copyNormal(File, newFile); } return true; }
}