Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

36
Chapter 9 1 Streams and File I/O CS-180 Recitation-03/07/2008
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    3

Transcript of Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Page 1: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 1

Streams and File I/O

CS-180

Recitation-03/07/2008

Page 2: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 2

Announcements

• Review session for Exam 2– Monday, March 17, 6:00-8:00 p.m.– LWSN B131

• Project 6 posted – Final Submission due March 26, 2008– Milestone Submission due March 20, 2008

Page 3: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 3

I/O Streams• An I/O Stream represents an input source or an

output destination• A stream can represent many different kinds of

sources and destinations- disk files, devices, other programs, a network socket- and memory arrays

• Streams support many different kinds of data- simple bytes, primitive data types, localized- characters, and objects

• Some streams simply pass on data; othersmanipulate and transform the data in useful ways.

Page 4: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 4

I/O• No matter how they work internally, all streams

present the same simple model to programs that use them– A stream is a sequence of bytes (data)– Data is transferred to devices by ‘streams‘

Program Data Sourceoutput - stream

Programinput - stream

Data Source

Page 5: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 5

Streams

• JAVA distinguishes between 2 types of streams:

• Text – streams, containing ‘characters‘I ‘ M A S T R I N G \nProgram Device

Binary Streams, containing information in 8-bit chunks

01101001Program Device11101101 00000000

Page 6: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 6

Streams• Streams in JAVA are Objects, of course ! • Having

– 2 types of streams (text / binary) and– 2 directions (input / output)– results in 4 base-classes dealing with I/O:

1. Reader: text-input2. Writer: text-output3. InputStream: byte-input4. OutputStream: byte-output

Page 7: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 7

The Concept of a Stream

• A stream is a flow of data (characters, numbers, etc.).

• Data flowing into a program is called an input stream.

• Data flowing out of a program is called an output stream.

Page 8: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 8

The Concept of a Stream, cont.

System.out is the only output stream we have used so far.

• Objects of class Scanner, used for keyboard input, are streams, too.

Page 9: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 9

Text Files and Binary Files

• All data in a file is stored as binary digits.– Files with contents that must be treated as

sequences of binary digits are called binary files; binary files can be read only by machines.

Page 10: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 10

Text Files and Binary Files,cont.

• Sometimes, it is more convenient to think of a file’s contents as a sequence of characters.– Files with streams and methods to make

them look like sequences of characters are called text files; text files can be read by people.

Page 11: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 11

Text Files vs Binary Files

• Example: writing of the integer ’42‘• TextFile: ‘4‘ ‘2‘ (internally translated to 2 16-

bit representations of the characters ‘4‘ and ‘2‘)

• Binary-File: 00101010, one byte • (= 42 decimal)

Page 12: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 12

Binary vs. TextFiles

pro con

Binary Efficient in terms of time and space

Preinformation about data needed to understand content

Text Human readable, contains redundant information

Not efficient

Page 13: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 13

Streams

Page 14: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 14

Text-File Output with PrintWriter

• Class PrintWriter has a method println that behaves like System.out.println

Page 15: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 15

Text-File Output with PrintWriter, cont.

• class TextFileOutputDemo

Page 16: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 16

Text-File Output with PrintWriter, cont.

• A file is opened using something similar tooutputStream = new PrintWriter(

new FileOutputStream(“out.txt”));

– An empty file is connected to a stream.– If the named file (out.txt, for example)

exists already, its old contents are lost.– If the named file does not exist, a new

empty file is created (and named out.txt, for example).

Page 17: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 17

Text-File Output with PrintWriter, cont.

• Class Printwriter has no constructor that takes a file name as an argument.

• So, we use class FileOutputStream to create a stream and can be used as an argument to a PrintWriter constructor.

• SyntaxPrintWriter Output_Stream_Name = new

PrintWriter (new

FileOutputStream(File_Name));

Page 18: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 18

Text-File Output with PrintWriter, cont.

• The FileOutputStream constructor, and thus the PrintWriter constructor invocation can throw a FileNotFoundException, which means that the file could not be created.

• The PrintWriter object is declared outside the try block.– If it were declared inside the try block, it

would be local to the try block.

Page 19: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 19

Some Methods in Class PrintWriter

• constructorPrintWriter(OutputStream streamObject)

• to create a new filenew PrintWriter(new

FileOutputStream(File_Name))

• to append new text to an old filenew PrintWriter(new

FileOutputStream(File_Name, true))

Page 20: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 20

Some Methods in Class PrintWriter, cont.

• to output to the file connected to the streampublic final void

println(Almost_Anything)

public final void

print(Almost_Anything)

• To close a stream’s connection to a filepublic void close()

• To flush the output streampublic void flush()

Page 21: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 21

Use toString for Text-File Output

• Classes typically include a method toString.• The methods println and print in class

PrintWriter behave like System.out.println and System.out.print, respectively.

Page 22: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 22

Use toString for Text-File Output, cont.

• class Species

Page 23: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 23

Use toString for Text-File Output, cont.

• class TextFileObjectOutputDemo

Page 24: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 24

Text-file Input with BufferedReader

• Class BufferedReader is the preferred stream class for reading from a text file.

• Class BufferedReader has no constructor that takes a filename as its argument.– Class FileReader accepts a file name as a

constructor argument and produces a stream that is a Reader object.

– The constructor for class BufferedReader accepts a Reader object as an argument.

Page 25: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 25

Text-file Input with BufferedReader, cont.

• syntaxBufferedReader Stream_Name = new

BufferedReader(new

FileReader(File_Name));

• Methods readln and read are used to read from the file.

• The FileReader constructor, and thus the BufferedReader constructor invocation can throw a FileNotFoundException.

Page 26: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 26

Text-file Input with BufferedReader, cont.

• class TextFileInputDemo

Page 27: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 27

Some Methods in Class BufferedReader

• constructor

BufferedReader(Reader, readerObject)• to create a stream

new BufferedReader(new

FileReader(File_Name))

• to read a line of input from the filepublic String readLine() throws IOException

– If the read operation goes beyond the end of the file, null is returned.

Page 28: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 28

Some Methods in Class BufferedReader, cont.

• to read a single character from the file and return it as an int valuepublic int read() throws IOException

– If the read operation goes beyond the end of the file, -1 is returned.

• to read a single character from the file and to treat it as a characterchar next = (char)(inputStream.read());

Page 29: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 30

Binary Files, cont.

• Class ObjectInputStream and class ObjectOutputStream are used to process binary files.– Data is read or written, one byte at a time.– Numbers and characters are converted

automatically to bytes for storage in a binary file.

– Data in files can be treated as Java primitive data types, as strings, or as other objects.

Page 30: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 31

Opening a Binary File

• syntaxObjectOutputStream Output_Stream_Name =

new ObjectOutputStream

(new FileOutputStream(File_Name));

• exampleObjectOutputStream myOutputStream =

new ObjectOutputStream

(new FileOutputStream

(“myfile.dat”));

Page 31: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 32

Output to Binary Files Using ObjectOutputStream

• class BinaryOutputDemo

Page 32: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 33

Some Methods in Class ObjectOutputStream,

cont.• to write a primitive type, cont.

public void writeLong(long n) throws

IOException

public void writeDouble(double x)

throws IOException

public void writeFloat(float x)

throws IOException

Page 33: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 34

Some Methods in Class ObjectOutputStream,

cont.public void writeChar(int n)

throws IOException

public void writeBoolean(boolean b)

throws IOException

• to write a Stringpublic void writeUTF(String aString)

throws IOException

Page 34: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 35

Some Methods in Class ObjectOutputStream,

cont.• To write an object

public void writeObject(Object

anObject)

throws IOException,

NotSerializableException,

InvalidClassException

• to closepublic void close() throws IOException

Page 35: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 37

import java.io.*; //for keyboard input methods

import java.util.*; //for StringTokenizer

public class TotalNumbers {

public static void main (String [] args) throws java.io.IOException {

String str, s;

int sum = 0, num;

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

System.out.print(“Enter four integers separated by spaces: “); //prompt

str = br.readLine( );

StringTokenizer st = new StringTokenizer(str);

while (st.hasMoreTokens( )) {

s = st.nextToken( );

num = Integer.parseInt(s);

sum += num; }

}

}

Page 36: Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008.

Chapter 9 38

Quiz

Write a program that will write your name to a text file.