java编程思想 IO8 文件操作源码

通道与缓冲器的探究

package com.dirlist;

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

public class ChannelCopy {
	private static final int BSIZE=1024;
	public static void main(String[] args) throws IOException {
		if(args.length!=2){
			System.out.println("arguments: sourcefile destfile");
			System.exit(1);
		}
		FileChannel in=new FileInputStream(args[0]).getChannel(),out=new FileOutputStream(args[1]).getChannel();
		ByteBuffer buff=ByteBuffer.allocate(BSIZE);
		//一旦调用read()来告知FileChannel向ByteBuffer存储字节,就必须调用缓冲器上的flip(),让它做好让别人读取字节的准备
		while(in.read(buff)!=-1){
			buff.flip();
			out.write(buff);
			//如果打算使用缓冲器执行进一步的read()操作,我们必须调用clear()方法
			buff.clear();//清除此缓冲区。将位置设置为零,限制设置为该容量,并且丢弃标记。 
		}
	}

}


package com.dirlist;

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

public class GetChannel {

	/**
	 * 新I/O 通道与缓冲器
	 */
	private static final int BSIZE=1024;
	public static void main(String[] args) throws IOException {
		//FileChannel用于读取、写入、映射和操作文件的通道。
		FileChannel fc=new FileOutputStream("data.txt").getChannel();
		//ByteBuffer字节缓冲区。wrap()将字节数组包装到缓冲区中。 
		//新的缓冲区将由给定的字节数组支持;也就是说,缓冲区修改将导致数组修改,反之亦然。新缓冲区的容量和界限将为 array.length,其位置将为零,其标记是不确定的。其底层实现数组将为给定数组,并且其数组偏移量将为零。
		
		fc.write(ByteBuffer.wrap("Some text ".getBytes()));
		fc.close();
		fc=new RandomAccessFile("data.txt","rw").getChannel();
		//position()设置此通道的文件位置。 
		//将该位置设置为大于文件当前大小的值是合法的,但这不会更改文件的大小。稍后试图在这样的位置读取字节将立即返回已到达文件末尾的指示。稍后试图在这种位置写入字节将导致文件扩大,以容纳新的字节;在以前文件末尾和新写入字节之间的字节值是未指定的。
		//size()返回此通道的文件的当前大小。
		System.out.println(fc.size());
		fc.position(fc.size());
		fc.write(ByteBuffer.wrap("Some more ".getBytes()));
		fc.close();
		fc=new FileInputStream("data.txt").getChannel();
		// allocate(int capacity)分配一个新的字节缓冲区。 
		ByteBuffer buff=ByteBuffer.allocate(BSIZE);
		fc.read(buff);
		//flip()反转此缓冲区。首先对当前位置设置限制,然后将该位置设置为零。如果已定义了标记,则丢弃该标记。 
		buff.flip();
		//hasRemaining()判断在当前位置和限制之间是否有任何元素。
		while(buff.hasRemaining()){
			System.out.print((char)buff.get());
		}

	}

}

 

package com.dirlist;

import java.nio.channels.FileChannel;
import java.io.*;
public class TransferTo {

	/**
	 * 如何将一个通道与另一个通道连接
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		if(args.length!=2){
			System.out.println("arguments : sourfile destfile");
			System.exit(1);
		}
		FileChannel in=new FileInputStream(args[0]).getChannel(),out=new FileOutputStream(args[1]).getChannel();
		in.transferTo(0, in.size(), out);
		//或者	out.transferFrom(in, 0, in.size());

	}

}

 

你可能感兴趣的:(java,编程)