Implementation of java file copy

Requirements: Implementing directory copy function (considering that there are subdirectories in the directory)

Analysis: To realize the copy of folder, I.O. stream is used to read and write files. Considering that there are subfolders in the folder, we need to use the idea of recurs io n to create the method of file copy. We can judge whether there are subfolders in the source file or not. In some cases, we can call this method to realize file traversal. Procedures are as follows

public class FileCopyUtils {

	/**
	 * Copy one source file object to another target file
	 * @param source  Source files (possibly directories)
	 * @param target  Target directory
	 * @throws IOException 
	 */
	public static void copy(File source,File targetDir) throws IOException{
		//Determine whether the current object to be copied is a directory or a standard file
		if(source.isDirectory()){
			//Create subdirectories in directories (nonexistent)
			targetDir = new File(targetDir,source.getName());
			if(!targetDir.exists()){
				//Attempt to create a directory if it does not exist
				if(!targetDir.mkdirs()){
					throw new FileNotFoundException("Directory creation failed,Please check permissions");
				}
			}
			//Read directory
			File[] files = source.listFiles();
			if(Objects.nonNull(files)){				
				for (int i = 0; i < files.length; i++) {
					copy(files[i],targetDir);
				}
			}
		}else{
			//File copy
			copyFile(source,targetDir);
		}
		
	}

	private static void copyFile(File source, File targetDir) throws IOException {
		BufferedInputStream bis = null;
		BufferedOutputStream bow = null;
		try{
			//Get the input stream of the source file and wrap it as a buffer stream
			bis = new BufferedInputStream(new FileInputStream(source));
			//Combining the target directory into a new file object based on the file name of the source file
			File target = new File(targetDir,source.getName());
			//Get the output stream of the target file
			bow = new BufferedOutputStream(new FileOutputStream(target));
			//Declare byte buffer to cache the read byte data
			byte[] b = new byte[1024];
			int len = 0;
			//Cyclic read and write
			while((len = bis.read(b)) != -1){
				bow.write(b, 0, len);
			}
		}finally{			
			//close resource
			if(bow != null)bow.close();
			if(bis != null)bis.close();
		}
	}
}
public class TestCopy {
	public static void main(String[] args) throws IOException {	
		//Source file
		File f1 = new File("D:/javacode"); 
		//Target file
		File f2 = new File("C:/Users/Administrator/Desktop"); 
		//Copy
		FileCopyUtils.copy(f1, f2);
	}
}

 

Posted on Thu, 10 Oct 2019 07:59:40 -0700 by yjanni