import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
*
* 从流中获得通道
* FileInputStream, FileOutputStream, RandomAccessFile
*
*/
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
//写文件
FileChannel fc = new FileOutputStream("d:\\a.txt").getChannel();
fc.write(ByteBuffer.wrap("This is a test for nio.\n".getBytes()));
fc.close();
//向文件末尾添加数据
fc = new RandomAccessFile("d:\\a.txt","rw").getChannel();
//定位到文件末尾
fc.position(fc.size());
fc.write(ByteBuffer.wrap("This is the end of file.".getBytes()));
fc.close();
//读文件
fc = new FileInputStream("D:\\a.txt").getChannel();
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
fc.read(bb);
//转换缓冲开关,由读转为写
bb.flip();
while(bb.hasRemaining()){
System.out.print((char)bb.get());
}
fc.close();
}
}
[java][nio]三种流获得可写/可读可写/可读的通道
最新推荐文章于 2024-01-31 15:11:38 发布