Transcript ppt

Chapter 9 – Part 1
Streams and File I/O




Chapter 9
Overview of Streams and File I/O
Text File I/O
Binary File I/O
File Objects and File Names
1
I/O Overview




I/O = Input/Output
the input to and output from programs
input comes from: keyboard or file
output sent to: display (screen) or file
– I/O is also exchanged via network communication

Advantages of using files
» permanent copy (program independent)
» exchange data between programs
» I/O can be automated (rather than manual)
Note: Since topics on text file I/O and binary file I/O have many similarities, some
duplicate (or nearly duplicate) discussions are presented.
Chapter 9
2
Streams

Stream: an object that either,
» sends data to its destination (screen, file, etc.) or
» accepts data from a source (keyboard, file, etc.)
» acts as a transmission/exchange buffer between
source and destination


Input stream: a stream providing input to a program
Output stream: a stream accepting output from a
program
» System.out is an output stream object
» System.in and SavitchIn are input streams objects
Chapter 9
3
Binary vs. Text Files

All data and programs are stored as 0's & 1's: binary
» bit is one binary digit (a 0 or 1)
» byte is a group of eight (8) bits

Text files: stored bits represent characters codes
» 1 byte per char. for ASCII, 1 bytes for Unicode
» ex: Java source code files are text files
» ex: "text editor" files, rather than wordprocessor files

Binary files: stored bits represent encoded data,
such as executable instructions, numeric, or images
» files can only be read by the computer, not humans
» they are not "printable" files, meaning the content isn't
simple ASCII (or Unicode)
Chapter 9
4
Java: Text Versus Binary Files


Text files are more readable by humans
Binary files are more efficient
» reading & writing binary files is easier than than text

Java binary files are portable
» can be used by Java progs. on different machines
» text files used only to communicate with humans****
Text Files


Chapter 9
Java source code
program and system
independent
Binary Files


type and program
specific files
are created and read by
programs
5
Text File I/O

Important classes for text file output (to a file)
» PrintWriter and FileOutputStream

Important classes for text file input (from a file)
» BufferedReader and FileReader

Note: FileOutputStream and FileReader are
used only for their constructors, to take a filename
and return a file stream object
» PrintWriter and BufferedReader can not use
file names as arguments

Add the following to program that use files:
import java.io.*;
Chapter 9
6
Every File Has Two Names

a file is related through two names,
» the name of the file (operating system)
– ex: out.txt
» the identifier of the stream object (program)
– ex: outputStream

Chapter 9
a good way to think of the relation of the two
names is that the, "in opening a file, the
stream object is attached to the filename."
7
Text File Output

open a text file for output: connect a text file to a
stream for writing,
» create a stream object of the class PrintWriter and
connect it to a text file (this creates/overwrites the file)
example:
PrintWriter outputStream =
new PrintWriter(newFileOutputStream("out.txt");

use .print() and .println() to write to the file
outputStream.println(count + " " + line);
(textbook lists other useful PrintWriter methods)
Chapter 9
8
TextFileOutputDemo
Part 1
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter (
new FileOutputStream("out.txt") );
}
catch(FileNotFoundException e)
{
// display "file opening error" and exit
System.out.println(e.message());
System.exit(0);
}
continued...
Chapter 9
9
TextFileOutputDemo
Part 2
String line = null;
int count;
// store input
// loop counter
System.out.println("Enter 3 lines of text:");
for (count = 1; count <= 3; count++)
{
line = SavitchIn.readLine();
outputStream.println (count+" "+line);
}
outputStream.close(); // close file
System.out.println("Written to out.txt.");
}// end of main()
Chapter 9
10
Gotcha: Overwriting a File

by default, opening a file for output,
» if the file does not exist, creates an empty file
» if the file exists, it is overwritten with an empty file and
the original data is lost

to prevent unintentional overwrite,
» check for existence of a file, using the File class
(page 570); or
» append data to the original file (page 551)
Chapter 9
11
Java Tip: Appending to a Text File

To add to a file instead of replacing it, use a different
constructor for FileOutputStream:
outputStream =
new PrintWriter(
new FileOutputStream("out.txt", true);

Second argument, true, indicates
» if file exists, append output to the end, do not replace
» if file does not exist, a new file is created, as expected
System.out.print ("A for append, or N for new file:");
char ans = SavitchIn.readLineNonWhiteChar();
boolean append = (ans == 'A' || ans = 'a');
outputStream = new PrintWriter(
new FileOutputStream("out.txt", append));
Chapter 9
12
Closing a File
Any opened must be closed!!

this is very important for files opened for output

use the close() method of the file stream
» outputStream.close();

why?
» if a program crashes, there is no expectation that the
OS will close open files correctly
» data is stored to a memory buffer before being sent to
a program (input) or a file (output);
if not closed properly, this buffer may not be emptied
(very bad for output)
Chapter 9
13
Text File Input

open a text file for input: connect a text file to a input
stream for reading,
» stream is of class BufferedReader
» use FileReader class with BufferedReader object
BufferedReader inputStream =
new BufferedReader(
new FileReader("datain.txt") );
» read a character (char) with .read()
» read lines (Strings) with .readLine()
» BufferedReader has no methods to read numerics,
so "parse" strings as before (i.e., Integer.parseInt() )
Chapter 9
14
Exception Handling with File I/O




IOException is a predefined class
file I/O done as described here might throw an
IOException
catch the exception in a catch-block that prints an
error message and [maybe] ends the program
FileNotFoundException is derived from
IOException
» any catch block that catches IOExceptions also
catches FileNotFoundExceptions
» use different catch blocks for each exception type, with
more specific ones first
Chapter 9
15
public static void main(String[] args)
{
String fileName = null;
try
{
System.out.println("Enter file name:");
fileName = SavitchIn.readLineWord();
BufferedReader inputStream =
new BufferedReader(new FileReader(fileName));
reading a file name
String line = null;
from the keyboard
line = inputStream.readLine();
System.out.println("The first line in " + filename + " is:");
using the file name
System.out.println(line);
// . . . code for reading second line not shown here . . .
read from the
inputStream.close();
keyboard
}
catch(FileNotFoundException e)
reading data
{
from the file
System.out.println("File " + filename + " not found.");
catch(IOException e)
multiple
{
catches
System.out.println("Error reading from file " + fileName);
}
}
Example:
Reading a
File Name
from the
Keyboard
16