现在的位置: 首页 > 综合 > 正文

NIO学习笔记(一)

2013年06月12日 ⁄ 综合 ⁄ 共 1188字 ⁄ 字号 评论关闭

指导文章来自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真的变得超级简单。测试过了,大的文件也没有问题,以前自己写的方法用来读写大文件的时候就经常是有错误的。但是,如果有其他需求的话呢?还真不知道如果搞定呢。

抱歉!评论已关闭.