Java Reference
In-Depth Information
We then proceed to call the
readAll()
method of
CSVReader
. This method reads the
contents of the CSV file and stores it into a
java.util.List
containing String arrays
as its elements. Each String array represents a row of values in the CSV file, mapping
them as they appear on the file. The
List
will have as many elements as there are
rows in the CSV file. The contents of our CSV file,
AircraftData.csv
, are as follows:
N263Y,T-11,39 ROSCOE TRNR RACER,R1830 SERIES
N4087X,BA100-163,BRADLEY AEROBAT,R2800 SERIES
N43JE,HAYABUSA 1,NAKAJIMA KI-43 IIIA,R1830 SERIES
N912S,9973CC,PA18-150,R-1820 SER
After reading the contents of this CSV file, the
CSVReader.readAll()
method will
return a list containing four arrays of Strings:
{"N263Y", "T-11", "39 ROSCOE TRNR RACER","R1830 SERIES"}
{"N4087X", "BA100-163", "BRADLEY AEROBAT","R2800 SERIES"}
{"N43JE", "HAYABUSA 1", "NAKAJIMA KI-43 IIIA","R1830 SERIES"}
{"N912S", "9973CC", "PA18-150","R-1820 SER"}
As we can see, the layout corresponds to the layout of the CSV file just described.
JasperReports datasources contain 'elements' and 'fields'. When using a database as
a datasource, a database row is considered as an element, and the columns as fields.
When using Java objects as datasources, each object is an element, and each attribute
of the object is a field. For our custom CSV datasource, each row in the CSV file is
considered an element, and each column, a field.
The
next()
method defined in
JRDataSource
moves the cursor to the next element
in the datasource. It returns a Boolean, indicating if the move was successful or not.
In our implementation, we have a
currentRowIndex
variable, indicating the current
element in the
List
returned by
CSVReader.readAll()
method. In the
next()
method, we increase the value of
currenRowIndex
by one, and return
false
if its
value is larger than the size of the list; otherwise, we return
true
.
The
getFieldValue()
method retrieves the value for the current field in the
datasource. It takes an instance of
net.sf.jasperreports.engine.JRField
class as
its only argument. The
JRField
interface contains a
getName()
method that is used
to retrieve the value of the field from its name. The way in which it is done depends
on the type of datasource. For example,
JRBeanCollectionDataSource
uses
utility classes from
Jakarta
commons-beanutils
to retrieve the bean's
property
value from its name.
JRXmlDataSource
uses a combination of
Xalan
, an XML
transformation library, and
Jakarta
commons
for its implementation.
For our
getFieldValue()
implementation, since a CSV file does not map names to
its fields, we simply ignore the parameter. All we do is obtain the array of strings in
the
List
returned by
CSVReader.readAll()
corresponding to
currentRowIndex
.
We, then, obtain the field corresponding to
currentColumnIndex
from it.