November 20, 2014
Hot Topics:

FileChannel Objects in Java, Records with Mixed Types

  • November 14, 2002
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Recap

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.

Summary

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:

Records
A 14 0.33333334
B 28 0.6666667

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

Bytes read = 14
File length = 14
Records
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;

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

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

      //Clear the ByteBuffer
      clearByteBufferData(bBuf,"bBuf");

      //Display the ByteBuffer to 
      // confirm that it has been
      // cleared.
      showRecords(bBuf);

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

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

    }catch(Exception e){
      System.out.println(e);}
  }// end main

  //---------------------------------//
  
  static void clearByteBufferData(
          ByteBuffer buf, String name){
    //Stores 0 in each element of a
    // byte buffer.
    
    //Set position to zero
    buf.position(0);
    System.out.println(
                      "Clear " + name);
    while(buf.hasRemaining()){
      buf.put((byte)0);
    }//end while loop
    //Set position to zero and return
    buf.position(0);
  }//end clearByteBufferData
  //---------------------------------//
  
  static void putRecord(
                       ByteBuffer bBuf,
                       char cData,
                       byte bData,
                       float fData){
    bBuf.putChar(cData);
    bBuf.put(bData);
    bBuf.putFloat(fData);
  }//end putRecord
  //---------------------------------//
  static void showRecords(
                      ByteBuffer bBuf){
    
    //Save position
    int pos = bBuf.position();
    //Set position to zero
    bBuf.position(0);
    System.out.println(
                   "Records");
    while(bBuf.hasRemaining()){
      System.out.println(
                bBuf.getChar() + " " + 
                bBuf.get() + " " + 
                bBuf.getFloat());
    }//end while loop
    System.out.println();//new line
    //Restore position and return
    bBuf.position(pos);
  }//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.

Baldwin@DickBaldwin.com

-end-
 



Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

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

Sitemap | Contact Us

Rocket Fuel