Reading and Writing Text Files Input/Output I/O Class Chapter 11
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
Java Class Libraries Required for I/O Streams import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter;
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.
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.
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); }
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); }
Sample Code