Java复制文件常用的三种方法
复制文件的三种方法:
1、Files.copy(path,newFileOutputStream(dest));。
2、利用字节流。
3、利用字符流。
代码实现如下:
packagecom.tiger.io;
importjava.io.*;
importjava.nio.file.*;
/**
*复制文件的三种方式
*@authortiger
*@Date
*/
publicclassCopyFile{
publicstaticvoidmain(String[]args)throwsIOException,IOException{
Pathpath=Paths.get("E:","17-06-15-am1.avi");
Stringdest="E:\\Copy电影.avi";
copy01(path,dest);
Stringsrc="E:\\[Java典型应用彻查1000例:Java入门].pdf";
Stringdest1="E:\\CopyFile.pdf";
copy02(src,dest1);
//copy03(src,dest1);
}
/**
*利用Files工具copy
*@parampath
*@paramdest
*@throwsIOException
*@throwsIOException
*/
publicstaticvoidcopy01(Pathpath,Stringdest)throwsIOException,IOException{
//利用Files工具类对文件进行复制,简化编程,只需要写一句。
Files.copy(path,newFileOutputStream(dest));
}
/**
*利用字节流复制
*@paramsrc
*@paramdest
*@throwsIOException
*/
publicstaticvoidcopy02(Stringsrc,Stringdest)throwsIOException{
InputStreamis=newBufferedInputStream(newFileInputStream(src));
OutputStreamos=newBufferedOutputStream(newFileOutputStream(dest));
//文件拷贝u,--循环+读取+写出
byte[]b=newbyte[10];//缓冲大小
intlen=0;//接收长度
//读取文件
while(-1!=(len=is.read(b))){
//读入多少,写出多少,直到读完为止。
os.write(b,0,len);
}
//强制刷出数据
os.flush();
//关闭流,先开后关
os.close();
is.close();
}
/**
*字符流复制
*@paramsrc
*@paramdest
*@throwsIOException
*/
publicstaticvoidcopy03(Stringsrc,Stringdest)throwsIOException{
//字符输入流
BufferedReaderreader=newBufferedReader(newFileReader(src));
//字符输出流
BufferedWriterwriter=newBufferedWriter(newFileWriter(dest));
char[]cbuf=newchar[24];
intlen=0;
//边读入边写出
while((len=reader.read(cbuf))!=-1){
writer.write(cbuf,0,len);
}
//关闭流
writer.close();
reader.close();
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接