JavaScript required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
Gallery
csHjavaA-2019
about this document
revision
traverse and process
standard algorithms
Parallel Arrays
read text files
write text files
CSV files
Letter frequency
development workflow
indices
More
Share
Explore
CSV files
council CSV example
demonstration of reading a CSV file into parallel arrays
fifa task
fifa write to file
CSV file format
the CSV file should contain a values like this
stored in CSV format with newline character after each line except for the last line
each line is a
pair of text values
separated by a
comma
, (there are no spaces)
each line has the same number of values
a CSV file is a standard way of storing a table of values, eg a spreadsheet or database
sometimes the first line will be used as a column heading
there can be 2 or more comma separated values on each line
using one CSV file avoids storing the different values in separate files, all the values can be read or written using one source/destination
A CSV file may contain a values like this (with headings)
reading values from a CSV file into parallel arrays
A Java read operation can read an entire file on a line from a file but not part of a line.
Each CSV line is read from the file as a string which has to be “unpacked” into parallel arrays
the comma is a separator between the two values
this long string must be
split
to give two
separate
values,
a string for "West Lothian"
an integer for 131295
In this case the data above will be stored in councilName[ ] a string array, and voters[ ] an integer array
split() is a string function that takes a string value and a separator (comma)
after splitting:
dataRowA[0] contains the string “West Lothian”
dataRowA[1] stores the string “131295”
the values from the array elements are copied to separate string and integer variabl
the string value “131295” is cast (converted) to the integer value 131395
All of the above work is repeated (using a loop) for each line from the file
writing a CSV file from parallel arrays
open file (for writing)
write a line with multiple values separated by commas to the CSV file (in a loop for multiple lines)
close the file
CSV file tasks
read from a CSV file
search for array values that match a target value
write only the matching values to a new file
original CSV with all councils
new CSV file with councils of fewer than 99999 voters
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
Ctrl
P
) instead.