public class MyUtil {
private MyUtil() {
throw new AssertionError();
}
/**
* 文件拷贝
* @param source 源文件名
* @param target 目标文件名
* @throws IOException 源文件不存在或者读写出错都会引发此异常
*/
public static void fileCopy(String source, String target) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
File f = new File(target);
File dir = f.getParentFile();
if(!dir.exists()) {
dir.mkdirs(); // 创建文件夹(如果父文件夹不存在则先创建父文件夹)
}
out = new FileOutputStream(target);
byte[] buffer = new byte[4096];
int bytesToRead = 0;
while((bytesToRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
}
finally {
if(in != null) { in.close(); }
if(out != null) { out.close(); }
}
}
}
package com.lovo;
import java.io.IOException;
import com.lovo.util.MyUtil;
class Test01 {
public static void main(String[] args) {
try {
MyUtil.fileCopy("c:/致橡树.txt", "e:/poem.txt");
MyUtil.fileCopy("d:/cs3/Sunset.jpg", "e:/Sunset.jpg");
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}