[quote]Allright 
The typical file sizes can be of variable degree. Anything from 1kb to 5mb ( that’s about a good range ).
There won’t be any processes other than the file transfer happening at the same time, I don’t see a need to thread the Server/ Client at this time.
By “best” I mean the best non error prone, logical, efficient way to send the files.
[/quote]
Without any special needs going on, I’d probably just do something like:
// Setup:
File f = new File( "/whereever/thingy" );
FileInputStream fis = new FileInputStream( f );
FileChannel rc = fis.getChannel();
...
// Loop:
int position = 0;
int fileLength = // length of file in bytes
if( position < fileLength )
{
rc.transferTo( position, fileLength-position, wbc );
}
else
{
out( "file transferred to nework Channel = "+wbc );
}
…where wbc is a SocketChannel returned from a ServerSocketChannel via:
SocketChannel wbc = ((ServerSocketChannel) key.channel()).accept();
The loop section that writes the file to the wbc would be in the middle of the network-non-blocking select, thus:
while( true )
{
try
{
selector.select();
Set keys = selector.selectedKeys();
Iterator i = keys.iterator();
while( i.hasNext() )
{
SelectionKey key = (SelectionKey) i.next();
i.remove();
if( key.isWritable() )
{
try
{
processWritableKey( key );
}
catch( IOException e )
{
key.cancel();
closeChannel( key.channel() );
}
}
else
out( "Unexpected: key \""+key+"\" is not writable; this Selector should only contain Writable keys...." );
}
}
…and the “processWritableKey” method initiates the loop that writes to the file. Obviously, you have to keep track of state etc, but you only asked “what’s the best way of doing this”, so I’m assuming you’re OK to fill in the blanks yourself.
That’s a good combination of “logical” and “efficient”. If you wanted ultra efficient, you could add bells and whistles, but with rapidly diminishing returns…If you don’t lke NIO, or don’t want to learn it, then you’ll be back to methods that are inherently inefficient, and so you have to work harder to try and squeeze out performance.
Generally, I trust methods like “transferTo” to work - unless I have special needs in a given situation (like “this has GOT to be REALLY REALLY fast!!!” ;)). Quoting from the API docs:
"This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them."