NIO学习笔记(一)

指导文章来自IBM:  http://www.ibm.com/developerworks/cn/education/java/j-nio/section5.html

 

I/O技术,是不得不学的,既然逃不过,就勇敢地面对吧。发现可以取巧,虽然我也不喜欢用这么一种封装过的工具类,但是说实话,确实好用。为什么不喜欢用呢?因为最精华的那部分代码,都被这工具类封装了,只是做调用方法的工作,是不能锻炼出很好的逻辑思维的。而现在要面临的是,我必须很快学会这I/O的操作,实现某些功能,那好吧,我也只能是先知其然,后再补补其所以然的道理。

 

今天就写了这么一个Demo,惭愧啊。。

 

package com.insigma.model;

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 InputStreamModel {
	public void readFile(){
		try {
			FileInputStream fin = new FileInputStream("D:/SoftWarePackage/tools/AdobeDreamweaverCS4_cn.exe");
			FileChannel fcin = fin.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			FileOutputStream fout = new FileOutputStream("testExe.exe");
			FileChannel fcout = fout.getChannel();
			
			while(true){
				buffer.clear();
				int r = fcin.read( buffer );
				if (r==-1) {
				     break;
				}
				buffer.flip();
				fcout.write( buffer );
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		InputStreamModel ism = new InputStreamModel();
		ism.readFile();
	}
}


如果单单是操作这些的话,那I/O真的变得超级简单。测试过了,大的文件也没有问题,以前自己写的方法用来读写大文件的时候就经常是有错误的。但是,如果有其他需求的话呢?还真不知道如果搞定呢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值