Java Nio
1 |
Java NIO Tutorial |
2 |
Java NIO Overview |
3 |
Java NIO Channel |
4 |
Java NIO Buffer |
5 |
java NIO scatter/gather |
6 |
Java NIO channel to channel transfers |
7 |
Java NIO Selector |
8 |
Java NIO FileChannel |
9 |
Java NIO Socketchannel |
10 |
Java NIO Serversocketchannel |
11 |
Java NIO Datagramchannel |
12 |
Java NIO Pipe |
13 |
Java NIO vs. IO |
Java NIO Channel to channel transfers
by Jakob JenkovConnect with me:
Rate article: Share Article:tweet
Table of Contents
- Transferfrom ()
- TransferTo ()
In Java NIO can transfer data directly from one channel to another, if one of the channels is a FileChannel
. The FileChannel
class has a and transferTo()
a transferFrom()
method which does.
Transferfrom ()
The FileChannel.transferFrom()
method transfers data from a source channel into the FileChannel
. Here are a simple example:
Randomaccessfile fromfile = new Randomaccessfile ("FromFile.txt", "RW"); FileChannel Fromchannel = Fromfile.getchannel (); Randomaccessfile tofile = new Randomaccessfile ("ToFile.txt", "RW"); FileChannel Tochannel = Tofile.getchannel (); Long position = 0;long count = Fromchannel.size (); Tochannel.transferfrom (Fromchannel, position, count);
position ), And how many bytes to transfer maximally (count
). If The source channel has fewer than count
Bytes, less is transfered.
Additionally, some implementations may transfer only the data the have ready on its SocketChannel
SocketChannel
internal buffer here and no W-even If the May later has more SocketChannel
data available. Thus, it may not be transfer the entire data requested () from the to count
SocketChannel
FileChannel
.
TransferTo ()
The transferTo()
method transfer from a into some and other FileChannel
channel. Here are a simple example:
Randomaccessfile fromfile = new Randomaccessfile ("FromFile.txt", "RW"); FileChannel Fromchannel = Fromfile.getchannel (); Randomaccessfile tofile = new Randomaccessfile ("ToFile.txt", "RW"); FileChannel Tochannel = Tofile.getchannel (); Long position = 0;long count = Fromchannel.size (); Fromchannel.transferto (position, count, Tochannel);
Notice How similar the example was to the previous. The only real difference are the which FileChannel
object the method is called on. The rest is the same.
The issue with was SocketChannel
also present with the transferTo()
method. SocketChannel
the implementation may be transfer bytes from FileChannel
the until the send buffer was full, and then stop.
Next: Java NIO Selector
Java NIO Channel to channel transfers