首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

JAVA FileChannel 兑现文件的COPY

2012-08-26 
JAVA FileChannel 实现文件的COPYimport java.io.FileInputStreamimport java.io.FileNotFoundException

JAVA FileChannel 实现文件的COPY

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class ChannelCopy {private static final int BSIZE =1024;public static void main(String[] args) {try {FileChannel in = new FileInputStream("ChannelCopy.java").getChannel(),out = new FileOutputStream("D:\\temp.txt").getChannel();ByteBuffer buffer = ByteBuffer.allocate(BSIZE);while((in.read(buffer))!=-1){buffer.flip();//做好被写的准备out.write(buffer);buffer.clear();//做好被读的准备}} catch (FileNotFoundException e) {System.out.println("找不到文件");} catch (IOException e) {e.printStackTrace();}}}/**简单写法**/import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.nio.channels.FileChannel;public class CopyOfChannel2 {public static void main(String[] args) {try {FileChannel in = new FileInputStream("ChannelCopy.java").getChannel(), out = new FileOutputStream("D:\\temp.txt").getChannel();in.transferTo(0, in.size(), out);//简便写法out.transferFrom(in, 0, in.size());//效果同上} catch (FileNotFoundException e) {System.out.println("找不到文件");} catch (IOException e) {e.printStackTrace();}}}
?

热点排行