Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java NIO with ByteBuffer

807603Jan 29 2008 — edited Jan 29 2008
Hi guys,

I search the forum and the web too, there are many pros and cons in relation to NIO, and on my free time I was trying to research about it, but there
are time when some things don't make any sense at all.

Without NIO:
    FileInputStream foin = new FileInputStream("/home/metitus/Desktop/test");
    FileOutputStream fout = new FileOutputStream("/home/metitus/Desktop/test1");

    int character = 0;

    while((character = foin.read()) != -1)
    {
        fout.write(character);
    }
with NIO:
FileInputStream foin = new FileInputStream("/home/metitus/Desktop/test");
    FileOutputStream fout = new FileOutputStream("/home/metitus/Desktop/test1");

    FileChannel fci = foin.getChannel();
    FileChannel fco = fout.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(1);

    while(fci.read(buffer) != -1)
    {
        buffer.flip();
        fout.write(buffer.array());
        buffer.clear();
    }
So guys where is the gain here? Why do I need a ByteBuffer always; it might be useful in some cases but definitely not in all.

MeTitus
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 26 2008
Added on Jan 29 2008
9 comments
326 views