Writing Output - Error With Varying Data Set Length

I have a problem writing out data from a data set. Here is my output logic:

FileWriter out = null;

try
{
session.log( "Writing data to a file." );

out = new FileWriter( "Data.txt", true );

out.write( session.getVariable ("VAR1") + ",");
out.write( dataSet.get( 0, "VAR2" ) + "," );
out.write( dataSet.get( 1, "VAR2" ) + "," );
out.write( dataSet.get( 2, "VAR2" ) + "," );
out.write( session.getVariable ("VAR3") + ",");
out.write( session.getVariable ("VAR4") + "\r\n");

// Close up the file.
out.close();

}
catch( Exception e )
{
session.log( "An error occurred while writing the data to a file: " + e.getMessage() );
}

All the variables except VAR2 are single value data points. VAR2 is a data set which can have zero to >20 records. I am trying to print out the first 3 records for VAR2. If the number of records for VAR2 is 3 or greater this works fine and I get a full line of data in the output. However, if the number of VAR2 records is 2 or fewer there is a write output error and none of the line is printed.

What I would like to see is a full line of data for each record set as follows:

1) Zero VAR2 records:

VAR1,Void,Void,Void,VAR3,VAR4

2) One VAR2 record:

VAR1,VAR2(0),Void,Void,VAR3,VAR4

3) Two VAR2 records:

VAR1,VAR2(0),VAR2(1),Void,VAR3,VAR4

4) Three or more VAR2 records:

VAR1,VAR2(0),VAR2(1),VAR2(2),VAR3,VAR4

I've tried all sorts of logic to make this happen without success. I'm sure there is a simple solution. Any ideas?