icon picker
read text files

key points about file handling, introductory projects, (includes substring)
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) :
normally displays like this:
text files can store digits but they are still represented as text characters rather than coded as integers
normally displays like this:

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
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)
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

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
Java needs to include additional features to make file handling work, add to the top of the program

dealing with file handling errors
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 (
) instead.