第一种拷贝方式:通过缓冲流和字节数组相结合
* @param src 源文件
* @param dest 目标文件
*/
public static boolean copy1(String src, String dest) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
boolean flag = false;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
byte[] data = new byte[1024*10];
int len;//向data数组中写入了几个数据
while((len=bis.read(data)) != -1){
bos.write(data,0,len);
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return flag;
}
/**
* 通过缓冲流拷贝,不采用小数组
* @param src
* @param dest
* @return
*/
public static boolean copy2(String src, String dest){
boolean flag = false;//标记我程序是否成功拷贝
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
int data;//每次读取到的数据
while((data = bis.read()) != -1){
bos.write(data);
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}finally{
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 采用普通字节输入输出流+小数组
* @param src
* @param dest
* @return
*/
public static boolean copy3(String src, String dest){
FileInputStream fis = null;
FileOutputStream fos = null;
boolean flag = false;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
byte[] data = new byte[1024*10];
int len;
while((len=fis.read(data)) != -1){
fos.write(data, 0, len);
}
flag = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
} |