JavaScript Required
We’re sorry, but Coda doesn’t work properly without JavaScript enabled.
Skip to content
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
write text files
writing text files and introducing CSV files
subject list
open, write and close a text file
capitalQuiz
open, write and close a CSV file
Here are the main steps for writing or saving text to a file and also some sample Java code to see how it works.
writing a file: main steps
open
file
write
to file
this will often involve a
loop
to repeat the write step for
every line
in a file
close
file
writing to file: java
open a text file
String outputFile = "results.txt";
PrintWriter fileWriter = new PrintWriter(outputFile);
store the name of the file
use the name of the file to create a PrintWriter for the file, call it fileWriter
if the file exists already then it will be overwritten
write next value from the array to the file(nest within a loop)
fileWriter.print(dataValues[i]);
access the value in the next position in the array and write it to the file
this code uses a loop index
[i]
to identify a position in a String array called textList
if
(i < subject.length-
1
) {
fileWriter.print(
"
\n
"
);
}
a newline character is needed between each line, that means after each value except for the last
the conditional checks that the loop index has not reached the end and inserts the newline after the value
close the file
fileWriter.close();
additional file handling code for Java
Java needs additional code to make file reading (and writing) work properly and to deal with any file errors
additional code needed for working with file in Java
import
java.util.*;
import
java.io.*;
Java needs to include additional features to make file handling work, add to the top of the program
dealing with file handling errors
throws
IOException
Java needs to know how to report any file errors, add this code at the start of methods that depend on file handling
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.