tags:

views:

110

answers:

3

Could someone explain to me the uses of using buffers, and perhaps some simple (documented) examples of a buffer in use. Thanks.

I lack much knowledge in this area of Java programming, so forgive me if I asked the question wrong. :s

+1  A: 

With a buffer, people usually mean some block of memory to temporarily store some data in. One primary use for buffers is in I/O operations.

A device like a harddisk is good at quickly reading or writing a block of consecutive bits on the disk in one go. Reading a large amount of data can be done very quickly if you tell the harddisk "read these 10,000 bytes and put them in memory here". If you would program a loop and get the bytes one by one, telling the harddisk to get one byte each time, it is going to be very inefficient and slow.

So you create a buffer of 10,000 bytes, tell the harddisk to read all the bytes in one go, and then you process those 10,000 bytes one by one from the buffer in memory.

Jesper
A: 

The Sun Java tutorials section on I/O covers this topic:

http://java.sun.com/docs/books/tutorial/essential/io/index.html

me_here
+2  A: 

A buffer is a space in memory where data is stored temporarily before it is processed. See Wiki article

Heres a simple Java example of how to use the ByteBuffer class.

Update

public static void main(String[] args) throws IOException 
{
    // reads in bytes from a file (args[0]) into input stream (inFile)
    FileInputStream inFile = new FileInputStream(args[0]);
    // creates an output stream (outFile) to write bytes to.
    FileOutputStream outFile = new FileOutputStream(args[1]);

    // get the unique channel object of the input file
    FileChannel inChannel = inFile.getChannel();
    // get the unique channel object of the output file.
    FileChannel outChannel = outFile.getChannel();    

    /* create a new byte buffer and pre-allocate 1MB of space in memory
       and continue to read 1mb of data from the file into the buffer until 
       the entire file has been read. */
    for (ByteBuffer buffer = ByteBuffer.allocate(1024*1024); inChannel.read(buffer) !=  1; buffer.clear()) 
    {
       // set the starting position of the buffer to be the current position (1Mb of data in from the last position)
       buffer.flip();
       // write the data from the buffer into the output stream
       while (buffer.hasRemaining()) outChannel.write(buffer);
    }

    // close the file streams.
    inChannel.close();
    outChannel.close();     
}

Hope that clears things up a little.

James
Perhaps you could copy that simple bit of code and document each line?
Rifk
Thanks for documenting it, really does help!
Rifk
+1 for documenting this ugly piece of code. Just look at that for- loop! The exception handling (no guarantee that channels are closed after)! I take it as an example for teaching my team to deliver clean code.
Andreas_D