通过通道来实现文件的复制,输入参数分别为sourceFile和destFile,表示要复制的文件,和复制完成后目标文件的名称
通过参数的形式输入,如果文件不可读或者不可写则抛出异常
package part18; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * Created by xueqin on 17/5/30. */ public class ChannelCopy { private static final int BSIZE=1024; public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("arguments:sourceFile destFile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } } }
解释:
首先通过判断参数长度是否为2来获取sourceFile,destFile的路径和名称
然后通过FileInputStream和FileOutoutStream,ByteBuffer来完成文件的循环复制。通过while循环来判断原文件是否还有未被复制的,直到全部被
复制,才结束。
当然通过通道的特殊方法transferTo()和transferFrom()方法允许我们直接把通道和通道相连
于是升级版的复制文件方法如下:
package part18; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; /** * Created by xueqin on 17/5/30. */ public class TransferTo { public static void main(String[] args) throws Exception{ if (args.length != 2) { System.out.println("arguments:sourceFile destFile" ); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); out.transferFrom(in, 0, in.size()); } }其中:in.transferTo和out.transferFrom都可以完成复制,两者实现的效果是相同的。除去参数判断。如果只写方法,则只有三行代码如下public static void copyFile(String sourceFile,String destFile) throws Exception { FileChannel in = new FileInputStream(sourceFile).getChannel(), out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); //out.transferFrom(in, 0, in.size()); }完工,可以看到很简单,以后再也不用担心写出文件复制代码而担心了。你需要的仅仅是两个参数,两个通道,一个transfer方法。