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
read text files
key points about file handling, introductory projects, (includes substring)
bookingDate
council names
file names
Scottish voters
internet domain names
Scottish Council voters
examScores
Here are the main steps for file handling and also some sample Java code to see who it works.
What do text files look like? 💾
One or more lines of text, each separated by a newline (
\n
) :
Aberdeen City
\n
Aberdeenshire
\n
Angus
\n
Argyll & Bute
\n
City of Edinburgh
(EndOfFile)
normally displays like this:
Aberdeen City
Aberdeenshire
Angus
Argyll & Bute
City of Edinburgh
text files can store digits but they are still represented as text characters rather than coded as integers
145832
\n
192269
\n
86548
\n
65512
\n
343748
(EndOfFile)
normally displays like this:
145832
192269
86548
65512
343748
reading a file: main steps
open
file
read
from file
this will often involve a
loop
to repeat the read step for
every line
in a file
close
file
reading from file: java
Reading text files is quite similar to reading a series of keyboard entries.
An attempt to read beyond the end of the file will normally cause an error and could cause the program to crash.
open a text file
// identify file
String inputFile =
"filename.txt"
;
// java file reader, opens file named by inputFile
Scanner fileReader =
new
Scanner(
new
File(inputFile));
store the name of the file
use the name of the file to create a Scanner for the file, call it fileReader
read next value from file as a String, store in an array (nest within a loop)
textList[i] = fileReader.nextLine();
read one line form the file and store it as text into the next position in the array
this code uses a loop index
[i]
to identify a position in a String array called textList
close the file
fileReader.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
What do text files look like? 💾
reading a file: main steps
reading from file: java
additional file handling code for Java
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.