设为首页 加入收藏

TOP

Java NIO入门(二)
2015-11-10 13:45:08 来源: 作者: 【 】 浏览:3
Tags:Java NIO 入门
lip();
fc.write(buffer);


实战练习


我们以一个名为 CopyFile.java 的简单程序作为这个练习的基础,它将一个文件的所有内容拷贝到另一个文件中。CopyFile.java 执行三个基本操作:首先创建一个Buffer,然后从源文件中将数据读到这个缓冲区中,然后将缓冲区写入目标文件。这个程序不断重复 ― 读、写、读、写 ― 直到源文件结束。


// CopyFile


import java.io.*;
import java.nio.*;
import java.nio.channels.*;


public class CopyFile {
? ?
? ? static public void main( String args[] ) throws Exception {
? ? ? ? String infile="E:\\北京欢迎你.txt";
? ? ? ? String outfile="E:\\out.txt";


? ? ? ? FileInputStream fin=new FileInputStream(infile);
? ? ? ? FileOutputStream fout=new FileOutputStream(outfile);
? ? ? ? FileChannel fcin = fin.getChannel();
? ? ? ? FileChannel fcout = fout.getChannel();


? ? ? ? ByteBuffer buffer = ByteBuffer.allocate(1024);


? ? ? ? while (true) {
? ? ? ? ? ? buffer.clear();
? ? ? ? ? ? int r=fcin.read(buffer);
? ? ? ? ? ? if (r == -1) {
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? ? ? buffer.flip();
? ? ? ? ? ? fcout.write(buffer);
? ? ? ? }
? ? }
}




首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python控制多进程与多线程并发数 下一篇Java读写文件方法总结

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: