本文共 1037 字,大约阅读时间需要 3 分钟。
使用NIO 写入数据与读取数据的过程类似,同样数据不是直接写入通道,而是写入缓冲区,可以分为下面三个步骤:
1. 从FileInputStream 获取Channel。
2. 创建Buffer。
3. 将数据从Channel 写入到Buffer 中。
import java.io.*;import java.nio.*;import java.nio.channels.*;public class FileInputDemo { static public void main( String args[] ) throws Exception { FileInputStream fin = new FileInputStream("E://test.txt"); // 获取通道 FileChannel fc = fin.getChannel(); // 创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取数据到缓冲区 fc.read(buffer); buffer.flip(); while (buffer.remaining() > 0) { byte b = buffer.get(); System.out.print(((char)b)); } fin.close(); }}
下面是一个简单的使用NIO 向文件中写入数据的例子:
import java.io.*;import java.nio.*;import java.nio.channels.*;public class FileOutputDemo { static private final byte message[] = { 83, 111, 109, 101, 32, 98, 121, 116, 101, 115, 46 }; static public void main( String args[] ) throws Exception { FileOutputStream fout = new FileOutputStream( "E://test.txt" ); FileChannel fc = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); for (int i=0; i
转载地址:http://itbzb.baihongyu.com/