Java file copy code snippet of Java implementation file copy
- 2020-04-01 02:46:20
- OfStack
One, to complete the program needs to understand the knowledge points:
1. Write simple Java programs like hello world -- crap... Ha ha
2. Understand Java file operation
3. Understand Java's buffer operation
4. Some exception handling points for file operations: 1. The case that the source file cannot be read. 2, the object file creation failure 3, the file lock problem 4, the character garbled code problem... Probably not
These are the packages that need to be used
Import the Java. IO. BufferedInputStream;
Import the Java. IO. BufferedOutputStream;
Import the Java. IO. FileInputStream;
Import the Java. IO. FileOutputStream;
Import the Java. IO. IOException; Exception handling is required for IO operations
Personal feeling this efficient way, the installation of the computer, efficient operation should be the operation of memory is relatively high, direct IO operation should be relatively low. Therefore, the choice here is to write IO when reading the internal existence. 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;
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 buffer it
inBuff = new BufferedInputStream(new FileInputStream(src));
//Create a new file output stream and buffer it
outBuff = new BufferedOutputStream(new FileOutputStream(des));
//The buffer array
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
//Refreshes the output stream of this buffer
outBuff.flush();
} finally {
//Close the stream
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
}
}
}
Other netizens added
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();
}