0% found this document useful (0 votes)
10 views

Lecture 16 - File Processing-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture 16 - File Processing-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Lecture 16: File

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

If the file doesn’t exist on the hard drive, it is created.


Step 2: Importing PrintWriter Class
Import the class using:
import java.io.PrintWriter;
Step 3: Writing a Line of Text
To write text to the file, we use the println() method from our
PrintWriter object:

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.

You might also like