Introduction to JAVA, Day 20, Copy Implementation of Files or Directories

Posted by randomfool on Tue, 30 Jul 2019 23:20:27 +0200

Copies of files or directories

This program involves IO streams, which are applied to the File Input Stream (File Output Sream) in IO streams. The learning of streams is very regular. They usually appear in pairs, and there are corresponding output streams with input streams (special hints, where the print stream is out of the column). Since this is a copy of the file, It must also involve calls to common methods of File classes.

Note that in this program, a very practical method is used, that is, the method callback (personal understanding, more like a circular statement, has been recycled, to reach a certain condition, like the end of the cycle) not much to say, above.  

There is no error after running: here I copy the contents of the Javacode folder of D disk to the javacode1 folder of E disk.

 


Effect:

This is the file on disk D.

  

This is the file on the E-disk:

    

The code is as follows:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

public class Test2 {

	public void findAll(File source, File target) {

		File[] file = source.listFiles();
		if (Objects.nonNull(file)) {
			for (int i = 0; i < file.length; i++) {
				File sour = file[i];
				File tar = new File(target, sour.getName());//Consideration of fault tolerance
//				if(!tar.exists()){
//					if(!tar.mkdir()){
//						System.out.println("Failure or Failure");
//					}
//				}
				if (sour.isFile()) {
					copy(sour, tar);
				} else {
					tar.mkdir();
					findAll(sour, tar);
				}
			}
		}
	}

	public void copy(File source, File target) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(source);
			fos = new FileOutputStream(target);
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = fis.read(b)) != -1) {
				fos.write(b, 0, len);
			}
		} catch (Exception e) {

		} finally {
			if (fis != null) {
				try {
					fis.close();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		File f1 = new File("D:\\javacode");
		File f2 = new File("E:\\javacode1");
		new Test2().findAll(f1, f2);

	}
}

Summary

Before realizing the copy of this file, I linked the File class, byte stream and so on. This method may not be the best way to write. It is suggested that we consider the problem of file fault tolerance (such as how to deal with the existing files). The implementation principle is basically the same. Before doing this method, we must To have an overall framework of IO flow in mind, it is possible to achieve twice the result with half the effort!

Topics: Java