通道Channel-使用NIO 写入数据
生活随笔
收集整理的這篇文章主要介紹了
通道Channel-使用NIO 写入数据
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用NIO 寫入數(shù)據(jù)與讀取數(shù)據(jù)的過程類似,同樣數(shù)據(jù)不是直接寫入通道,而是寫入緩沖區(qū),可以分為下面三個步驟:
1. 從FileInputStream 獲取Channel。
2. 創(chuàng)建Buffer。
3. 將數(shù)據(jù)從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();// 創(chuàng)建緩沖區(qū)ByteBuffer buffer = ByteBuffer.allocate(1024);// 讀取數(shù)據(jù)到緩沖區(qū)fc.read(buffer);buffer.flip();while (buffer.remaining() > 0) {byte b = buffer.get();System.out.print(((char)b));}fin.close();} }下面是一個簡單的使用NIO 向文件中寫入數(shù)據(jù)的例子:
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<message.length; ++i) {buffer.put( message[i] );}buffer.flip();fc.write( buffer );fout.close();} }?
總結
以上是生活随笔為你收集整理的通道Channel-使用NIO 写入数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通道Channel-使用NIO 读取数据
- 下一篇: 通道Channel-IO 多路复用