Java程序片:Java复制文件
生活随笔
收集整理的這篇文章主要介紹了
Java程序片:Java复制文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種方法(輸入輸出流):
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();//得到對應的文件通道FileChannel outChannel=new FileOutputStream(out).getChannel();//得到對應的文件通道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);//連接兩個通道,并且從in通道讀取,然后寫入out通道 }}finally {if ( inChannel != null ) { inChannel.close(); } if ( outChannel != null ) { outChannel.close(); } }}對比:
FileChannel復制文件的速度比輸入輸出流方式復制文件的速度快。在復制大文件的時候更加體現出FileChannel的速度優勢。而且FileChannel是多并發線程安全的。
轉載于:https://www.cnblogs.com/coder9527/p/6606656.html
總結
以上是生活随笔為你收集整理的Java程序片:Java复制文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces 766E
- 下一篇: java美元兑换,(Java实现) 美元