六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 97|回复: 0

Java NIO入门

[复制链接]

升级  78.33%

133

主题

133

主题

133

主题

举人

Rank: 3Rank: 3

积分
435
 楼主| 发表于 2013-1-15 01:58:39 | 显示全部楼层 |阅读模式
 
package com.ls.java.newio;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 CopyFile {public static void main(String[] args) {String infile = "/home/astute/comm/01_select.sql";String outfile = "/home/astute/comm/copy_to_new.sql";try {// 获取源文件和目标文件的输入输出流FileInputStream is = new FileInputStream(infile);FileOutputStream os = new FileOutputStream(outfile);// 获取输入输出通道FileChannel fcin = is.getChannel();FileChannel fcout = os.getChannel();// 创建缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);while(true) {// clear方法重设缓冲区,使它可以接受读入的数据buffer.clear();// 从输入通道中将数据读到缓冲区int r = fcin.read(buffer);// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1if(r == -1)break;// flip方法让缓冲区可以将新读入的数据写入另一个通道// 写模式转换成读模式buffer.flip();// 从输出通道中将数据写入缓冲区fcout.write(buffer);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}} 
Buffer常见方法:

flip():写模式转换成读模式

rewind():将position重置为0,一般用于重复读。

clear():清空buffer,准备再次被写入(position变成0limit变成capacity)

compact():将未读取的数据拷贝到buffer的头部位。

mark()reset():mark可以标记一个位置,reset可以重置到该位置。

Buffer常见类型:ByteBuffer MappedByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer

 
 
 
 
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表