Download presentation
Presentation is loading. Please wait.
1
Reading and Writing Text Files
Input/Output I/O Class Chapter 11
2
Streams Streams are defined as a sequence of Data
Input Stream is used to read data from a source Output Stream is used to write data to a destination
3
Java Class Libraries Required for I/O Streams
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter;
4
Scanner A Scanner class object is used to read input from a disk file.
Scanner relies on the File class to read and write data to files.
5
How to Read files using Scanner and File objects:
Construct a File object with the name of the input file: File inputFile = new File(“file.txt”); Use the File object to construct a Scanner object Scanner in = new Scanner(inputFile); Create a text file with content and save the file with a .txt extension.
6
How to Read files using Scanner and File objects:
3. Process the stream to read text from the input file (“file.txt”) while(in.hasNextLine()) { String content = in.nextLine(); System.out.print(content); }
7
Class Practice Problem Create a Java Class to read contents of a file.
Create a class:FileStreams Add a java class: ReadWrite.java Add required libraries listed on slide3 Construct a File object for streaming data Construct a Scanner object for receiving file content Write a while loop to get file data and send to the monitor(S.O.P) while(in.hasNext()) { String content=in.nextLine(); System.out.println(content); }
8
Sample Code
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.