Java Three Commonly Used Methods of Copying Files

  • 2021-07-03 00:02:46
  • OfStack

Three Ways to Copy Files:

1. Files. copy (path, new FileOutputStream (dest)); .

2. Use byte streams.

3. Use character stream.

The code is implemented as follows:


package com.tiger.io;
import java.io.*;
import java.nio.file.*;
/**
 *  Of the copy file 3 A kind of way 
 * @author tiger
 * @Date 
 */
public class CopyFile {
 public static void main(String[] args) throws IOException, IOException {
 Path path = Paths.get("E:","17-06-15-am1.avi");
 String dest = "E:\\Copy Movie .avi";
 copy01(path, dest);
 String src = "E:\\[Java Thorough investigation of typical applications 1000 Example: Java Getting started ].pdf";
 String dest1 = "E:\\CopyFile.pdf";
 copy02(src, dest1);
 //copy03(src, dest1);
 }
 
 /**
 *  Utilization Files Tools copy
 * @param path
 * @param dest
 * @throws IOException
 * @throws IOException
 */
 public static void copy01(Path path,String dest) throws IOException, IOException{
 // Utilization Files The tool class copies the file , Simplify programming, just write 1 Sentence. 
 Files.copy(path, new FileOutputStream(dest));
 }
 
 /**
 *  Copy with byte stream 
 * @param src
 * @param dest
 * @throws IOException
 */
 public static void copy02(String src,String dest) throws IOException{
 InputStream is = new BufferedInputStream(new FileInputStream(src));
 OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
 // File copy u , --  Cycle + Read + Write out 
 byte[] b = new byte[10];// Buffer size 
 int len = 0;// Receiving length 
 // Read a file 
 while (-1!=(len = is.read(b))) {
  // Read in and write out as much as you can until you finish reading. 
  os.write(b,0,len);
 }
 // Forcibly brush out data 
 os.flush();
 // Close the flow, open first and then close 
 os.close();
 is.close();
 }
 
 /**
 *  Character stream copy 
 * @param src
 * @param dest
 * @throws IOException
 */
 public static void copy03(String src,String dest) throws IOException{
 // Character input stream 
 BufferedReader reader = new BufferedReader(new FileReader(src));
 // Character output stream 
 BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
 char[] cbuf = new char[24];
 int len = 0;
 // Write out while reading in 
 while ((len = reader.read(cbuf)) != -1) {
  writer.write(cbuf, 0, len);
 }
 // Close flow 
 writer.close();
 reader.close();
 }
}

Summarize


Related articles: