1、使用字节流快速copy文件;
// 使用try-resource-with,系统自动关闭资源,资源需要实现Closeable接口或者继承AutoCloseable类
// 1、选择流
try (InputStream is = new FileInputStream("test5.txt");
OutputStream os = new FileOutputStream("test6.txt");) {
// 2、准备读取
int len = 0;
// 3、读取
while ((len = is.read()) != -1) {
//4 、写入文件
os.write(len);
}
// 5、刷新输出流
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2、使用字符流快速copy文件;
// 使用try-resource-with,系统自动关闭资源,资源需要实现Closeable接口或者继承AutoCloseable类
// 1、选择流
try (Reader reader = new FileReader("test6.txt");
Writer writer = new FileWriter("test7.txt");) {
// 2、准备读取
char[] datas = new char[10];
int len = 0;
// 3、读取
while ((len = reader.read(datas)) != -1) {
//4 、写入文件
writer.write(datas, 0, datas.length);
}
// 5、刷新输出流
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
3、使用Apache Commons IO的FileUtils工具类快速copy文件;
// 下载地址:http://commons.apache.org/proper/commons-io/download_io.cgi
// 第一个参数源文件,第二个参数目标文件
FileUtils.copyFile(new File(“test4.txt”), new File(“test5.txt”));