通道Channel-使用NIO 寫入資料
阿新 • • 發佈:2021-01-12
使用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<message.length; ++i) { buffer.put( message[i] ); } buffer.flip(); fc.write( buffer ); fout.close(); } }