Java程序片:Java复制文件
生活随笔
收集整理的這篇文章主要介紹了
Java程序片:Java复制文件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種方法(輸入輸出流):
public void copyFile(File fromFile,File toFile) throws Exception{FileInputStream in=new FileInputStream(fromFile);FileOutputStream out=new FileOutputStream(toFile);byte[] buffer=new byte[1024];while((in.read(buffer))!=-1){out.write(buffer, 0, buffer.length);}in.close();out.flush();out.close();}第二種方法(文件通道):
public void fileCopy( File in, File out ) throws IOException {FileChannel inChannel=new FileInputStream(in).getChannel();//得到對(duì)應(yīng)的文件通道FileChannel outChannel=new FileOutputStream(out).getChannel();//得到對(duì)應(yīng)的文件通道try{//inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows // magic number for Windows, 64Mb - 32Kb) int maxCount=(64*1024*1024)-(32*1024);long size=inChannel.size();long position=0;while(position<size){position+=inChannel.transferTo(position, maxCount, outChannel);//連接兩個(gè)通道,并且從in通道讀取,然后寫入out通道 }}finally {if ( inChannel != null ) { inChannel.close(); } if ( outChannel != null ) { outChannel.close(); } }}對(duì)比:
FileChannel復(fù)制文件的速度比輸入輸出流方式復(fù)制文件的速度快。在復(fù)制大文件的時(shí)候更加體現(xiàn)出FileChannel的速度優(yōu)勢(shì)。而且FileChannel是多并發(fā)線程安全的。
轉(zhuǎn)載于:https://www.cnblogs.com/coder9527/p/6606656.html
總結(jié)
以上是生活随笔為你收集整理的Java程序片:Java复制文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces 766E
- 下一篇: 201521123113 《Java程序