write text files

icon picker

open, write and close a CSV file

developer task

study the project notes on this page to understand how to write values to a CSV file
fork the project and test the code with some text values
create a new project to implement a solution to the exercise at the foot of this page
you should have read the general notes about writing a file

program requirement: write a CSV file (example)

allow a user to enter a set of country names and the capital cities of the countries
save the pairs of country and capital values to a CSV file

CSV file output

the results 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

java constructs for CSV output

open file (for writing)
write a line with multiple values separated by commas to the CSV file (in a loop for multiple lines)
fileWriter.print(country[i] + "," + capital[i]);
close the file

program code


exercise: Christmas list

program requirement: write a Christmas list of names and presents to a new CSV file
create a new repl project
allow a user to enter a set of names and a Christmas present for the person
save the pairs of names and presents to a file

the results file should end up like this
my cousin,a better sense of humourmy dog,robot dog walkermy neighbour,a new house somewhere else

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.