1. Knowledge points you need to know to complete this program:
1. Write a simple Java program, such as hello world --- nonsense. . . . Ha ha
2. Understand java file operations
3. Understand the buffer operation of java
4. Some exception handling points for file operations: 1. The source file cannot be read. 2. Failed to create the destination file. 3. File lock problem. 4. Character garbled problem. . . Maybe not all
These are the packages needed
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; Exception handling is required during IO operations
Personally, I feel that this efficient method, when it comes to installing a computer, the most efficient operation should be relatively high in memory operations, and relatively low in direct IO operations. . So what I choose here is to read the memory and write IO uniformly. The code is as follows:
package com.itheima;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/** * 5. Write a copy of the program file, try to use the most efficient method. * * @author [email protected] * * 1. The source file cannot be read. 2. Failed to create the destination file 3. File lock problem 4. Character garbled problem */public class Test5 {public static void main(String[] args) throws IOException {String src_file = "D:/java/java.doc" ;String des_file = "D:/java/java_copy.doc";copyFile(src_file, des_file);System.out.println("OK!");}public static void copyFile(String src, String des) throws IOException {BufferedInputStream inBuff = null;BufferedOutputStream outBuff = null;try {// Create a new file input stream and compare it It buffers inBuff = new BufferedInputStream(new FileInputStream(src));// Create a new file output stream and buffer it outBuff = new BufferedOutputStream(new FileOutputStream(des));// Buffer array byte[] b = new byte[1024 * 5];int len;while ((len = inBuff.read( b)) != -1) {outBuff.write(b, 0, len);}// Flush this buffered output stream outBuff.flush();} finally {//Close the stream if (inBuff != null)inBuff.close();if (outBuff != null)outBuff.close();}}}
Supplements from other netizens
try { File inputFile = new File(args[0]); if (!inputFile.exists()) { System.out.println("The source file does not exist, the program terminates"); System.exit(1); } File outputFile = new File(args[1]); InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile); byte date[] = new byte[1024]; int temp = 0; while ((temp = in.read(date)) != -1) { out.write(date); } in.close(); out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }