Java IO programming - file copy

Keywords: Java JDK

There is a copy command in the operating system. The main function of this command is to realize the file copy processing. Now it is required to simulate this command and realize the file copy processing by inputting the copy source file path and the copy target path through initialization parameters.

Demand analysis:

If you need to copy files, it is possible to copy various types of files, so you must use byte stream;

· when copying, it may be necessary to consider the copying of large files;

Implementation plan:

Scheme 1: use InputStream to directly read all the contents to be copied into the program, and then output them to the target file at one time;

| - if the files copied now are large, basically the program will die;

Scheme 2: use partial copy to read part of the output part of the data. If you want to use the second method now, the core operation method is:

      |- InputStream: public int read​(byte[] b) throws IOException;

      |- OutputStream: public void write​(byte[] b,int off, int len) throws IOException;

Example: file copy processing

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 class FileUtil {    // Define a tool class for file operation
 7     private File srcFile ; // Source file path
 8     private File desFile ; // Destination file path
 9     public FileUtil(String src,String des) {
10         this(new File(src),new File(des)) ;
11     }
12     public FileUtil(File srcFile,File desFile) {
13         this.srcFile = srcFile ;
14         this.desFile = desFile ;
15     }
16     public boolean copy() throws Exception {    // File copy processing
17         if (!this.srcFile.exists()) {    // Source file must exist!
18             System.out.println("The copied source file does not exist!");
19             return false ; // Copy failure
20         }
21         if (!this.desFile.getParentFile().exists()) { 
22             this.desFile.getParentFile().mkdirs() ; // Create parent directory
23         }
24         byte data [] = new byte[1024] ; // Create a copy buffer
25         InputStream input = null ;
26         OutputStream output = null ;
27         try {
28             input = new FileInputStream(this.srcFile) ;
29             output = new FileOutputStream(this.desFile) ;
30             int len = 0 ;
31             // 1,Read the data into the array, and then return the number of reads len = input.read(data
32             // 2,Judge whether the number is-1,If not, write(len = input.read(data)) != -1
33             while ((len = input.read(data)) != -1) {
34                 output.write(data, 0, len);
35             }
36             return true ; 
37         } catch (Exception e) {
38             throw e ;
39         } finally {
40             if (input != null) {
41                 input.close();    
42             } 
43             if (output != null) {
44                 output.close() ;
45             }
46         }
47     }
48 }
49 public class JavaAPIDemo {
50     public static void main(String[] args) throws Exception {
51         if (args.length != 2) {    // Program execution error
52             System.out.println("Command execution error, execution structure: java JavaAPIDemo Copy source file path copy target file path");
53             System.exit(1); 
54         }
55         long start = System.currentTimeMillis() ;
56         FileUtil fu = new FileUtil(args[0],args[1]) ;
57         System.out.println(fu.copy() ? "File copy succeeded!" : "File copy failed!");
58         long end = System.currentTimeMillis() ;
59         System.out.println("Copy completed:" + (end - start));
60     }
61 }
JavaAPIDemo

  

  

However, it should be noted that the above method belongs to the original implementation of file copying. Since JDK 1.9, InputStream and Reader classes have data transfer processing methods appended:

      ·InputStream: public long transferTo​(OutputStream out) throws IOException;

      ·Reader: public long transferTo​(Writer out) throws IOException;

Example: use transfer to store

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 class FileUtil {    // Define a tool class for file operation
 7     private File srcFile ; // Source file path
 8     private File desFile ; // Destination file path
 9     public FileUtil(String src,String des) {
10         this(new File(src),new File(des)) ;
11     }
12     public FileUtil(File srcFile,File desFile) {
13         this.srcFile = srcFile ;
14         this.desFile = desFile ;
15     }
16     public boolean copy() throws Exception {    // File copy processing
17         if (!this.srcFile.exists()) {    // Source file must exist!
18             System.out.println("The copied source file does not exist!");
19             return false ; // Copy failure
20         }
21         if (!this.desFile.getParentFile().exists()) { 
22             this.desFile.getParentFile().mkdirs() ; // Create parent directory
23         }
24         InputStream input = null ;
25         OutputStream output = null ;
26         try {
27             input = new FileInputStream(this.srcFile) ;
28             output = new FileOutputStream(this.desFile) ;
29             input.transferTo(output) ;
30             return true ; 
31         } catch (Exception e) {
32             throw e ;
33         } finally {
34             if (input != null) {
35                 input.close();    
36             } 
37             if (output != null) {
38                 output.close() ;
39             }
40         }
41     }
42 }
43 public class JavaAPIDemo {
44     public static void main(String[] args) throws Exception {
45         if (args.length != 2) {    // Program execution error
46             System.out.println("Command execution error, execution structure: java JavaAPIDemo Copy source file path copy target file path");
47             System.exit(1); 
48         }
49         long start = System.currentTimeMillis() ;
50         FileUtil fu = new FileUtil(args[0],args[1]) ;
51         System.out.println(fu.copy() ? "File copy succeeded!" : "File copy failed!");
52         long end = System.currentTimeMillis() ;
53         System.out.println("Copy completed:" + (end - start));
54     }
55 }
JavaAPIDemo

Pay attention to the running version of the program at this time. If we want to extend this program further, can we copy a file directory? Once the file directory is copied, the files in all subdirectories need to be copied.

 

Example: folder copy

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileOutputStream;
 4 import java.io.InputStream;
 5 import java.io.OutputStream;
 6 class FileUtil {    // Define a tool class for file operation
 7     private File srcFile ; // Source file path
 8     private File desFile ; // Destination file path
 9     public FileUtil(String src,String des) {
10         this(new File(src),new File(des)) ;
11     }
12     public FileUtil(File srcFile,File desFile) {
13         this.srcFile = srcFile ;
14         this.desFile = desFile ;
15     }
16     public boolean copyDir() throws Exception {
17         try {
18             this.copyImpl(this.srcFile) ;
19             return true ;
20         } catch (Exception e) {
21             return false ; 
22         }
23     }
24     private void copyImpl(File file) throws Exception {    // Recursive operation
25         if (file.isDirectory()) {    // Directory
26             File results [] = file.listFiles() ; // List all directory components
27             if (results != null) {
28                 for (int x = 0 ; x < results.length ; x ++) {
29                     copyImpl(results[x]) ;
30                 }
31             }
32         } else {    // It's a document.
33             String newFilePath = file.getPath().replace(this.srcFile.getPath() + File.separator, "") ;
34             File newFile = new File(this.desFile,newFilePath) ; // Destination path of the copy
35             this.copyFileImpl(file, newFile) ;
36         }
37     }
38     private boolean copyFileImpl(File srcFile,File desFile) throws Exception {
39         if (!desFile.getParentFile().exists()) { 
40             desFile.getParentFile().mkdirs() ; // Create parent directory
41         }
42         InputStream input = null ;
43         OutputStream output = null ;
44         try {
45             input = new FileInputStream(srcFile) ;
46             output = new FileOutputStream(desFile) ;
47             input.transferTo(output) ;
48             return true ;
49         } catch (Exception e) {
50             throw e ;
51         } finally {
52             if (input != null) {
53                 input.close();    
54             } 
55             if (output != null) {
56                 output.close() ;
57             }
58         }
59     }
60     
61     public boolean copy() throws Exception {    // File copy processing
62         if (!this.srcFile.exists()) {    // Source file must exist!
63             System.out.println("The copied source file does not exist!");
64             return false ; // Copy failure
65         }
66         return this.copyFileImpl(this.srcFile, this.desFile) ;
67     }
68 }
69 public class JavaAPIDemo {
70     public static void main(String[] args) throws Exception {
71         if (args.length != 2) {    // Program execution error
72             System.out.println("Command execution error, execution structure: java JavaAPIDemo Copy source file path copy target file path");
73             System.exit(1); 
74         }
75         long start = System.currentTimeMillis() ;
76         FileUtil fu = new FileUtil(args[0],args[1]) ;
77         if (new File(args[0]).isFile()) {    // File copy
78             System.out.println(fu.copy() ? "File copy succeeded!" : "File copy failed!");
79         } else {    // directories copying
80             System.out.println(fu.copyDir() ? "File copy succeeded!" : "File copy failed!");
81         }
82         long end = System.currentTimeMillis() ;
83         System.out.println("Copy completed:" + (end - start));
84     }
85 }
JavaAPIDemo
This program is the core code of IO operation. It is very easy to understand the entire IO processing mechanism.

Posted by fiddler80 on Sat, 09 Nov 2019 02:41:22 -0800