文件克隆
例题一:使用带缓冲区的字节流实现文件的克隆。
使用BufferedInputStream和BufferedOutputStream来实现文件的复制
import java.io.*;
/**
* 添加缓冲区之后的字节流的拷贝
*/
public class TestCopy2 {
public static void main(String[] args) {
copy("源文件",",目标文件");
}
public static void copy(String src,String data){
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
//选择流
try {
bis=new BufferedInputStream(new FileInputStream(src));
bos=new BufferedOutputStream(new FileOutputStream(data));
//使用流
byte[] bytes=new byte[1024];
//定义一次读取的容量长度
int len=0;
while ((len=bis.read(bytes))!=-1){
//写数据
bos.write(bytes,0,len);
//手动刷新,以防忘关流
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭输入流
try {
if(bis!=null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
//关闭输出流
try {
if (bos!=null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
例题二:使用带缓冲区的字符流实现文件的克隆
使用BufferedReader和BufferedWriter来实现文件的复制
import java.io.*;
/**
* 带缓冲区字符流
*/
public class TestCopy3 {
public static void main(String[] args) {
bfCopy("源文件","目标文件");
}
public static void bfCopy(String src,String date){
//选择流
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader(src));
bw=new BufferedWriter(new FileWriter(date));
//声明一个字符数组
char[] flag=new char[1024];
//用来获取文件中字节的个数
int len;
//直到读取到最后长度为-1
while ((len=br.read(flag))!=-1){
//写数据
bw.write(flag,0,len);
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
try {
if (br!=null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bw!=null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}