文件的復制
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 將文件復制到指定的目錄
*/
public class CopyFile {
public static void main(String[] args) {
// 將F盤下的test.txt文件復制到D盤
System.out.println("開始復制。。");
copy("F:/test.txt", "D:/test.txt");
System.out.println("復制成功!");
}
public static void copy(String src, String dest) {
// 准備復制源文件和目的地
File srcFile = new File(src);
File destFile = new File(dest);
// 准備輸入輸出流
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] flush = new byte[1024];
int len = -1;
// 邊讀邊寫
while ((len = in.read(flush)) != -1) {
out.write(flush, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉原則,先用后關
// 關閉輸出流
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 關閉輸入流
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}// copy
}