1. 文本文件的复制
@Test
public void test4() {
FileReader fr = null;
FileWriter fw = null;
try {
File srcFile = new File("src\\echo06\\hello.txt");
File destFile = new File("src\\echo06\\hello1.txt");
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
char[] cuff = new char[5];
int len;
while ((len = fr.read(cuff)) != -1) {
fw.write(cuff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 非文本文件的复制
@Test
public void test5() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File("src\\echo06\\earth.jpg");
File destFile = new File("src\\echo06\\earth1.jpg");
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 完整文件复制
public class CopyFile {
public static void main(String[] args) {
CopyFile cf = new CopyFile();
long start = System.currentTimeMillis();
String srcPath = "D:\\Data\\earth.mp4";
String destPath = "D:\\Data\\earth(1).mp4";
cf.copyFileBuffered(srcPath, destPath);
long end = System.currentTimeMillis();
System.out.println("spend time:" + (end - start));
}
public void copyFileStream(String srcPath, String destPath) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert fos != null;
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void copyFileBuffered(String srcPath, String destPath) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert bos != null;
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}