public
class
fileniocopydemo
/** * 複製兩個資源目錄下的檔案
*/private
static
void
niocopyresourcefile()
private
static
void
niocopyfile
(string sourcepath, string destpath)
long starttime = system.
currenttimemillis()
; fileinputstream fis = null;
fileoutputstream fos = null;
filechannel inchannel = null;
filechannel outchannel = null;
try//切換buffer為寫模式
buffer.
clear()
;}//強制重新整理到磁碟
outchannel.
force
(true);
}finally
}catch
(ioexception e)
}private
static
void
closeutil
(closeable item)
catch
(ioexception e)}}
}
客戶端傳送public
class
niosendclient
/** * 向伺服器傳輸檔案
*/private
void
sendfile()
//獲取原始檔流
fileinputstream fileinputstream =
newfileinputstream
(srcfile)
;//獲取原始檔通道
filechannel filechannel = fileinputstream.
getchannel()
;//獲取socket通道
socketchannel socketchannel = socketchannel.
open()
;//連線服務端
socketchannel.
connect
(new
inetsocketaddress
(niodemoconfig.socket_server_ip, niodemoconfig.socket_server_port));
//設定channel為非阻塞
socketchannel.
configureblocking
(false);
//自旋,等待連線完成
while
(!socketchannel.
finishconnect()
) system.out.
println
("client成功連線伺服器端");
//傳送檔名稱
bytebuffer filenamebytebuffer = charset.
encode
(destpath)
; socketchannel.
write
(filenamebytebuffer)
;//傳送檔案長度
bytebuffer buffer = bytebuffer.
allocate
(niodemoconfig.send_buffer_size)
; buffer.
putlong
(srcfile.
length()
);buffer.
flip()
; socketchannel.
write
(buffer)
; buffer.
clear()
;//傳送檔案內容
system.out.
println
("開始傳輸檔案");
int length =0;
long progress =0;
while
((length = filechannel.
read
(buffer)
)>0)
//判斷檔案傳輸結束,傳送結束符至對端
if(length ==-1
) system.out.
println
("*****= 檔案傳輸成功 *****==");
}catch
(exception e)
}private
static
void
closeutil
(closeable item)
catch
(ioexception e)}}
}
客戶端public
class
udpclient
public
void
send()
throws ioexception
//關閉資料報信道
channel.
close()
;}}
服務端public
class
udpserver
public
void
receive()
throws ioexception
} iterator.
remove()
;}}}
NIO 簡單筆記
public static void main string args throws ioexceptionbytebuffer 介面有4個類實現,字尾r表示唯讀。不可執行put方法,一旦執行,直接丟擲異常,原始碼其實就是就是new乙個異常。directbytebuffer,directbytebu...
NIO 簡單筆記
public static void main string args throws ioexceptionbytebuffer 介面有4個類實現,字尾r表示唯讀。不可執行put方法,一旦執行,直接丟擲異常,原始碼其實就是就是new乙個異常。directbytebuffer,directbytebu...
NIO簡單理解(一,NIO服務端簡單實現邏輯)
熟悉nio,首先要理解nio核心物件 serversocketchannel selector 是乙個多路開關選擇器,可以同時檢查 如果需要,也可以等待 一組通道的i o狀態,能夠管理多個通道上的i o操作。簡單nio服務端為例實現邏輯 建立selector 多路開關選擇器或者通道管理器 幹的事就是...