chapter 9 1 chapter 9 – part 1 l overview of streams and file i/o l text file i/o l binary file...

16
Chapter 9 Chapter 9 – Part 1 Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Streams and File I/O

Upload: dinah-jones

Post on 01-Jan-2016

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 1

Chapter 9 – Part 1

Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names

Streams and File I/O

Page 2: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 2

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.

Page 3: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 3

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

Page 4: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 4

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)

Page 5: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 5

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 Java source code program and system

independent

Binary Files type and program specific

files are created and read by

programs

Page 6: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 6

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.*;

Page 7: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 7

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

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."

Page 8: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 8

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 fileoutputStream.println(count + " " + line);

(textbook lists other useful PrintWriter methods)

Page 9: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 9

TextFileOutputDemoPart 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...

Page 10: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 10

TextFileOutputDemoPart 2

String line = null; // store input

int count; // 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()

Page 11: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 11

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)

Page 12: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 12

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

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

Java Tip: Appending to a Text File

Page 13: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 13

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)

Page 14: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 14

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() )

Page 15: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Chapter 9 15

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

Page 16: Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O

Example:Reading a File Name

from the Keyboard

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)); String line = null; line = inputStream.readLine(); System.out.println("The first line in " + filename + " is:"); System.out.println(line); // . . . code for reading second line not shown here . . . inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File " + filename + " not found."); catch(IOException e) { System.out.println("Error reading from file " + fileName); } }

16

reading a file name from the keyboard

using the file name read from the keyboard

reading data from the file

multiple catches