Lecture 16 - File Processing-1
Lecture 16 - File Processing-1
Processing
COMP102: Computer Programming
Sibonelo Dlamini
2 October 2024
Agenda
- Why are files important
- How to read from a text file
- How to write to a text file
- Demo in jGrasp on how to read and write to a text file
The Importance of Files
1. Persist data/information from one run to the next (saving
progress made on assignment)
2. Allow for the transfer of data/information (updating
status, sharing memes)
3. Organise our data
Reading from a Text File
Step 1: File and Scanner Classes
We’re used to using the Scanner to read input from the user:
Scanner input = new Scanner(System.in);
We can also use the Scanner to read file, but first we need to create a File
object:
File myFile = new File(“myFile.txt”);
Scanner fileInput = new Scanner(myFile);
Step 2: Importing File Class
We need to import the File class like we do the Scanner:
import java.io.File;
Step 3: Import IOException Class
As expected, the IOException class is also in the java.io package:
import java.io.IOException;
Step 4: Reading a Line of Text
All of the Scanner methods you’re used to are available:
input.nextLine()
input.nextInt()
input.nextDouble()
Often, we’ll process more than one line. To do this we use the pattern:
while(input.hasNext()) {
// Process the next line
}
Writing to Text File
Step 1: The PrintWriter Class
We use a new class called a PrintWriter:
PrintWriter ouput = new PrintWriter(“myFile.txt”);
output.println(“First line”);
Finally, Close Your Files!
Close Scanner and PrintWriter
Objects
Always remember to close your streams (Scanner and
PrintWriter objects):
output.close();
input.close();
Ends.