`

java.nio.channels.FileChannel(文件通道)

    博客分类:
  • Java
阅读更多

旧I/O类库中有三被改进了,可以产生FileChannel,它们是:FileInputStream、FileOutputStream 以及可读可写的RandomAccessFile 。Reader和Writer字符模式类不能用于产生通道,但是java.nio.channels.Channels类能提供实用方法在通道中产生Reader和Writer。

 

public static void main(String[] args) throws Exception {
		// 写文件
		FileChannel fc = new FileOutputStream("data.txt").getChannel();
		fc.write(ByteBuffer.wrap("Some text ".getBytes()));
		fc.close();
		// 在文件尾写入
		fc = new RandomAccessFile("data.txt", "rw").getChannel();
		fc.position(fc.size()); // 移到文件尾
		fc.write(ByteBuffer.wrap("Some more".getBytes()));
		fc.close();
		// 读文件
		fc = new FileInputStream("data.txt").getChannel();
		ByteBuffer buff = ByteBuffer.allocate(1024);
		fc.read(buff);
		buff.flip();
		while (buff.hasRemaining())
			System.out.print((char) buff.get());
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics