write text files

icon picker
subject list

open, write and close a text file

developer task

study the project notes on this page to understand how to write values to a simple text 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 text file (example)

ask a user to type a series of five subject names, store the names in an array
write the array values to a text file

text file: output

the results file should contain a list with a value on each line
FrenchArt and DesignBiologyDanceComputing Science
stored in text format with newline character after each line except for the last line
French\nArt and Design\nBiology\nDance\nComputing Science

java code constructs to write to a file

open file
String outputFile = "subjects.txt";PrintWriter fileWriter = new PrintWriter(outputFile);
• choose a name for the file and open it for writing
write (a line) to file
if (i<subject.length-1) { fileWriter.print("\n");} // end if
• use fileWriter with print to output a line of text
• a newline should be added after each line of text, apart from the last line
this code will be nested within a loop to repeat for each value in the array
close file

program code


exercise: binary headings

write a list to a text file for the binary place headings for 8 bite two’s complement starting with -128
create a new repl project
enter the values using the keyboard
store the number values in an integer array
write them to a text file

the results file should end up like this

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