Java中channel用法總結(jié)
本文實例總結(jié)了Java中channel用法。分享給大家供大家參考。具體分析如下:
1.Channel接口的定義:
public interface Channel
{
public boolean isOpen( );
public void close( ) throws IOException;
}
2.Channel的常見類型:
FileChannel, SocketChannel, ServerSocketChannel, and DatagramChannel;
FileChannel通過RandomAccessFile, FileInputStream, FileOutputStream的getChannel()來初始化。
SocketChannel sc = SocketChannel.open();
sc.connect (new InetSocketAddress ("somehost", someport));
ServerSocketChannel ssc = ServerSocketChannel.open( );
ssc.socket().bind (new InetSocketAddress (somelocalport));
DatagramChannel dc = DatagramChannel.open();
3.Scatter/Gather,必須使用ByteBuffer.allocateDirect(100)
public interface ScatteringByteChannel extends ReadableByteChannel {
public long read (ByteBuffer [] dsts) throws IOException;
public long read (ByteBuffer [] dsts, int offset, int length) throws IOException;
}
public interface GatheringByteChannel extends WritableByteChannel {
public long write(ByteBuffer[] srcs) throws IOException;
public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;
}
4.file lock是和file相關(guān),而不是channel??梢詫M(jìn)程有效,而不是線程??梢酝ㄟ^內(nèi)存映射文件(memory-mapped file)來實現(xiàn)線程同步
5.buffer = fileChannel.map (FileChannel.MapMode.READ_ONLY, 100, 200);
6.MappedByteBuffer are direct. load( )將整個文件加載到內(nèi)存(改方法不能保證完成)。force( )將數(shù)據(jù)flush到硬盤。
7.未綁定端口的DatagramChannel系統(tǒng)會自動分配端口。DatagramChannel的connect(),將保證只接受指定源地址的數(shù)據(jù)包。這時候,可以使用普通的read和write方法,包括Scatter/Gather
希望本文所述對大家的java程序設(shè)計有所幫助。
相關(guān)文章
詳解SpringBoot修改啟動端口server.port的四種方式
這篇文章主要介紹了詳解SpringBoot修改啟動端口server.port的四種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD)
本篇文章主要介紹了Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Java虛擬機(jī)JVM性能優(yōu)化(三):垃圾收集詳解
這篇文章主要介紹了Java虛擬機(jī)JVM性能優(yōu)化(三):垃圾收集詳解,本文講解了眾多的JVM垃圾收集器知識點,需要的朋友可以參考下2014-09-09
使用Lombok導(dǎo)致打印的tostring中缺少父類的屬性問題
使用Lombok時,若發(fā)現(xiàn)@Data注解的@ToString不包含父類屬性,可通過添加@ToString(callSuper=true)解決,此方法確保在生成toString()時包括父類的屬性,有效解決只打印子類屬性的問題,這種做法對于需要完整信息展示的場景尤為重要2024-11-11
SpringBoot實現(xiàn)過濾器、攔截器與切片的實現(xiàn)和區(qū)別
本文詳細(xì)介紹了使用過濾器、攔截器與切片實現(xiàn)每個請求耗時的統(tǒng)計,并比較三者的區(qū)別與聯(lián)系,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
Java實現(xiàn)一鍵將Word文檔轉(zhuǎn)為PDF
在開發(fā)中,經(jīng)常會碰到需要把 Word 文檔轉(zhuǎn)換成 PDF 格式的需求,Java 有不少好用的庫能實現(xiàn)這個功能,本文為大家介紹了兩個常用的方法,需要的可以了解下2025-02-02

