Java 文件的拷贝
package cn.io;
import java.io.*;
/**
* @author Duoduo
* @version 1.0
* @date 2017/4/16 20:54
*/
public class Test2 {
public static void main(String[] args) {
fileCopy();
}
public static void fileCopy() {
File srcFile = new File("/Users/Pengjinjin/JAVAStudy/IDEA Project/src/main/java/cn/io/Test.java");
File desFile = new File("/Users/Pengjinjin/Desktop/2.txt");
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(desFile);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fileInputStream.read(buffer)) != -1) {
//此处需要注意写入的一定是文件读取的长度,而不是buffer的长度,否则buffer中为空的数据也会写入到文件中
fileOutputStream.write(buffer,0, length);
}
fileOutputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}