Download presentation
Presentation is loading. Please wait.
1
Streams & File Input/Output (I/O)
2
I/O Streams A java stream is an object consisting of a sequence of bytes that flow from a source to a destination Stream Destination Source Source: A program, a file Destination: Can be a file, the console (i.e. output) window….. We read information from an input stream and write information to an output stream
3
I/O Streams Streams are a bit of an elusive concept in Java -- it can take a while to get used to them You sort of need to mentally try to picture them over and over again, and the idea of them begins to become clear The java.io.* (input output or I/O for short) package contains many classes that allow us to define various kinds of streams, each with specific characteristics A program can manage multiple streams at a time The I/O package is quite complex and a detailed analysis of all the classes in this package requires practice and experience
4
I/O Streams categories
There are several categories of I/O streams Today we will limit ourselves to two I/O streams. The first kind of stream deals with reading information from text files. The second deals with writing information to text files. Here are the classes that we will use for each: FileReader: To read lines of text from files PrintWriter: To write lines of text to files
5
Standard I/O We have already dealt with 3 standard I/O streams
A standard input stream– defined by System.in A standard output stream – defined by System.out A standard error stream– defined by System.err Yet we never had to create these streams. This is because these streams are very common and are therefore automatically created for us as soon as we start executing a program
6
Streams are objects: System.out System.in
out is a field of the System class. The data type of ‘out’ is a class called PrintStream You could also say that ‘out’ is an object of type PrintStream println is a method of the PrintStream class. System.in in is an object of type InputStream read is a method that read only raw byte data
7
Scanner to the rescue Instead of having to deal with the System.in “rawness” we were able to use a Scanner object Scanner console = new Scanner (System.in); And the handy methods like next(), nextInt(), nextDouble() etc. to read from the console Today we will see how to use Scanner to read from a text file
8
Reading from files Instead of using System.in (i.e. the terminal keyboard) as our input source, we need to create an input source linked to a text file To do this, we need a special stream class, called FileReader The FileReader class has methods that will connect the Scanner class to a specific text file which can then be read
9
Reading from files The Scanner class has a very convenient method called nextLine() that reads in a line from a text file. So, once we have linked the Scanner class to an input file, we can use the nextLine() method to read in each line of the file The nextLine() method returns a String containing the first line of the file. The method also positions the cursor at the beginning of the next line
10
import java.util.*; import java.io.*; public static void main(String[] args) { } throws FileNotFoundException FileReader dataFile = new FileReader("data.txt"); ); Scanner fileIn = new Scanner (dataFile); while (fileIn.hasNextLine()) { } String aLine = fileIn.nextLine(); System.out.println(aLine); fileIn.close();
11
The four steps of file reading
Import the necessary packages (java.io.*) Create an input stream to the input source: FileReader object to the actual file Scanner associated to the FileReader Use the appropriate methods to read the data: nextLine() , nextInt(), etc. Close the stream: fileIn.close()
12
File I/O Can Generate Exceptions
If the program doesn’t find the file or if the file is somehow protected and denies access, the program will throw an exception and abort (crash) Every time you use FileReader you need to either handle or throw the exception or it will not compile We can handle by enclosing the I/O code inside a try/catch sequence. Or, we can simply throw (delegate) with: throws FileNotFoundException
13
import java.util.*; import java.io.*; public static void main(String[] args) { } throws FileNotFoundException FileReader dataFile = new FileReader(“data.txt”); Scanner fileIn = new Scanner ( dataFile); while (fileIn.hasNextLine()) { } String aLine = fileIn.nextLine(); System.out.println(aLine); fileIn.close();
14
The four+ steps of file reading
Import the necessary packages (java.io.*) Create an input stream to the input source: FileReader object to the actual file Scanner associated to the FileReader Use the appropriate methods to read the data: nextLine() , nextInt(), etc. Close the stream: fileIn.close() Handle or throw the FileNotFoundException
15
Writing to a file We need to create an output stream that is connected to a file For this, we do not use FileReader and Scanner We make use of the PrintWriter stream class and its methods
16
import java.util.*; import java.io.*; public static void main(String[] args) { } throws FileNotFoundException PrintWriter fileOut = new PrintWriter("data.txt"); String aLine = "A line of text"; fileOut.println(aLine); fileOut.close();
17
The four+ steps of file writing
Import the necessary packages (java.io.*) Create an output stream to the output source: PrintWriter object to the actual file Use the appropriate methods to write the data: println() , print(), etc. Close the stream: fileOut.close()
18
Important: What happens when a program attempts to open a file that does not yet exist depends on whether it is for input or output For input: If the file does not exist, an exception will be thrown and the program will stop For output: If the file does not exist PrintWriter will create the file and not throw an exception If the output file already exists, then the PrintWriter object will overwrite the file that was previously there!
19
Printing to file When PrintWriter writes to an existing file, it overrides whatever is already there, e.g. it does not append So if you do not want to lose what you already have you should: store the existing data in memory, then write the old and the new using PrintWriter
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.