将文档从一个地方拷贝到另一个地方有很多种方法,以下是一个通过文件通道将文件进行复制,从而达到文件拷贝的效果。
具体代码如下:
1 package com.zcb.test; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.nio.channels.FileChannel; 8 9 public class FileCopyUtil { 10 //复制文件 11 public static void fileChannelCopy(File sources, File dest){ 12 FileInputStream inputStream = null; 13 FileOutputStream outputStream = null; 14 FileChannel fileChannepn = null; 15 FileChannel fileChannelout = null; 16 try { 17 18 inputStream = new FileInputStream(sources); 19 outputStream = new FileOutputStream(dest); 20 fileChannepn = inputStream.getChannel();//得到对应的文件通道 21 fileChannelout = outputStream.getChannel();//得到对应的文件通道 22 fileChannepn.transferTo(0, fileChannepn.size(), fileChannelout);//连接两个通道,并且从in通道读取,然后写入out通道 23 24 } catch (Exception e) { 25 e.printStackTrace(); 26 }finally{ 27 try{ 28 if(inputStream!=null){ 29 inputStream.close(); 30 } 31 if(fileChannepn!=null){ 32 fileChannepn.close(); 33 } 34 35 if(outputStream!=null){ 36 outputStream.close(); 37 } 38 if(fileChannelout!=null){ 39 fileChannelout.close(); 40 } 41 42 }catch(IOException e){ 43 e.printStackTrace(); 44 } 45 46 } 47 } 48 //测试方法 49 public static void main(String[] args) throws Exception { 50 51 File sources= new File("C:/Users/hspcadmin/Desktop/待复制文档.docx"); 52 File dest= new File("C:/Users/hspcadmin/Desktop/复制/复制文档.docx"); 53 fileChannelCopy(sources,dest); 54 55 } 56 }