March 5, 2021
Hot Topics:

FileChannel Objects in Java, Records with Mixed Types

  • By Richard G. Baldwin
  • Send Email »
  • More Articles »


To recap, this program:

  • Creates a ByteBuffer object
  • Creates two data records each consisting of a char value, a byte value, and a float value and stores the two records in the ByteBuffer object
  • Uses a FileChannel object to write the records in the ByteBuffer object to a disk file
  • Clears the ByteBuffer object
  • Uses a FileChannel object to read the records from the disk file back into the ByteBuffer object
  • Displays the two records in the ByteBuffer object

Happily, the output shown in Figure 4 matches the original contents of the two records, confirming that there was no data corruption during the round trip.

That's it for now

By now you should understand a quite a lot about the use of the FileChannel class and the ByteBuffer class to create records containing mixed primitive types, to store those records in a disk file, and to manipulate the records after reading them from the disk file.

Run the Program

If you haven't already done so, I encourage you to copy the code from Listing 12 into your text editor, compile it, and execute it.  Experiment with it, making changes, and observing the results of your changes.

Remember, however, that you must be running Java version 1.4.0 or later to compile and execute this program.


In this lesson, I have taught you how to use the FileChannel class along with the ByteBuffer class to:

  • Create records consisting of sequences of data values of mixed primitive types
  • Manipulate those records under program control
  • Transfer those records between the computer's memory and a physical file

What's Next?

In the next lesson, I will teach you how to use the FileChannel class to perform memory-mapped IO.

Future plans

As time goes on, I plan to publish additional lessons that will help you learn to use other new IO features including:

  • File locks
  • Character-set encoders and decoders
  • Pattern matching on files using regular expressions
  • Socket channels for both clients and servers
  • Non-blocking reads
  • Non-blocking servers

Complete Program Listing

A complete listing of the program discussed in this lesson is shown in Listing 12 below.
/* File Channel03.java
Copyright 2002, R.G.Baldwin
Revised 9/23/02

Illustrates use of FileChannel objects
to write and read data of different 
types from a disk file.

Writes and reads data where the
ByteBuffer contains records of mixed
types.  Each record contains a char,
a byte, and a float.

Tested using JDK 1.4.0 under Win2000

The output is:

A 14 0.33333334
B 28 0.6666667

Bytes written = 14
File length = 14
Clear bBuf
  0 0.0
  0 0.0

Bytes read = 14
File length = 14
A 14 0.33333334
B 28 0.6666667

import java.io.*;
import java.nio.channels.*;
import java.nio.*;

class Channel03{
  public static void main(
                        String[] args){
    //Create a ByteBuffer with a 
    // capacity of 56 bytes, and all
    // elements initialized to zero.
    ByteBuffer bBuf = 
        ByteBuffer.wrap(new byte[56]);

    //Declare varables for use later
    FileOutputStream oStr;
    FileInputStream iStr;
    FileChannel fileChan;

      // Set ByteBuffer limit to 
      // capacity
      //Store two records of mixed data
      // types in the ByteBuffer
      char cData = 'A';
      byte bData = 14;
      float fData = (float)1.0/3;
      cData = 'B';
      bData = 28;
      fData = (float)2.0/3;
      //Set limit to position and then
      // set position to 0
      //Display records in ByteBuffer
      //Get FileChannel for output
      oStr = new FileOutputStream(
      fileChan = oStr.getChannel();

      //Write output data from the
      // ByteBuffer to the disk file.
               "Bytes written = " 
               + fileChan.write(bBuf));
      //Close stream and channel and
      // display file size
                      "File length = " 
                    + fileChan.size());

      //Clear the ByteBuffer

      //Display the ByteBuffer to 
      // confirm that it has been
      // cleared.

      //Get FileChannel for input
      iStr = new FileInputStream(
      fileChan = iStr.getChannel();

      //Read data from disk file into
      // ByteBuffer.  Then display 
      // records in the ByteBuffer
                "Bytes read = " 
                + fileChan.read(bBuf));
      //Close stream and channel and
      // display file size
                      "File length = " 
                    + fileChan.size());
      //Display records

    }catch(Exception e){
  }// end main

  static void clearByteBufferData(
          ByteBuffer buf, String name){
    //Stores 0 in each element of a
    // byte buffer.
    //Set position to zero
                      "Clear " + name);
    }//end while loop
    //Set position to zero and return
  }//end clearByteBufferData
  static void putRecord(
                       ByteBuffer bBuf,
                       char cData,
                       byte bData,
                       float fData){
  }//end putRecord
  static void showRecords(
                      ByteBuffer bBuf){
    //Save position
    int pos = bBuf.position();
    //Set position to zero
                bBuf.getChar() + " " + 
                bBuf.get() + " " + 
    }//end while loop
    System.out.println();//new line
    //Restore position and return
  }//end showDoubleBufferData

}//end class Channel03 definition

Listing 12

Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which has gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.



Page 3 of 3

This article was originally published on November 14, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date