Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 91 Streams and File I/O CS-180 Recitation-03/07/2008."— Presentation transcript:

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

2 Chapter 92 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

3 Chapter 93 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; others manipulate and transform the data in useful ways.

4 Chapter 94 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 Source output - stream Program input - stream Data Source

5 Chapter 95 Streams JAVA distinguishes between 2 types of streams: Text – streams, containing ‘characters‘ I ‘M A STRING\n ProgramDevice Binary Streams, containing information in 8-bit chunks 01101001 ProgramDevice 1110110100000000

6 Chapter 96 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-input 2.Writer: text-output 3.InputStream: byte-input 4.OutputStream: byte-output

7 Chapter 97 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.

8 Chapter 98 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.

9 Chapter 99 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.

10 Chapter 910 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.

11 Chapter 911 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)

12 Chapter 912 Binary vs. TextFiles procon Binary Efficient in terms of time and space Preinformation about data needed to understand content Text Human readable, contains redundant information Not efficient

13 Chapter 913 Streams

14 Chapter 914 Text-File Output with PrintWriter Class PrintWriter has a method println that behaves like System.out.println

15 Chapter 915 Text-File Output with PrintWriter, cont. class TextFileOutputDemo

16 Chapter 916 Text-File Output with PrintWriter, cont. A file is opened using something similar to outputStream = 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).

17 Chapter 917 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. Syntax PrintWriter Output_Stream_Name = new PrintWriter (new FileOutputStream(File_Name));

18 Chapter 918 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.

19 Chapter 919 Some Methods in Class PrintWriter constructor PrintWriter(OutputStream streamObject) to create a new file new PrintWriter(new FileOutputStream(File_Name)) to append new text to an old file new PrintWriter(new FileOutputStream(File_Name, true ))

20 Chapter 920 Some Methods in Class PrintWriter, cont. to output to the file connected to the stream public final void println(Almost_Anything) public final void print(Almost_Anything) To close a stream’s connection to a file public void close() To flush the output stream public void flush()

21 Chapter 921 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.

22 Chapter 922 Use toString for Text-File Output, cont. class Species

23 Chapter 923 Use toString for Text-File Output, cont. class TextFileObjectOutputDemo

24 Chapter 924 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.

25 Chapter 925 Text-file Input with BufferedReader, cont. syntax BufferedReader 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.

26 Chapter 926 Text-file Input with BufferedReader, cont. class TextFileInputDemo

27 Chapter 927 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 file public String readLine() throws IOException –If the read operation goes beyond the end of the file, null is returned.

28 Chapter 928 Some Methods in Class BufferedReader, cont. to read a single character from the file and return it as an int value public 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 character char next = (char)(inputStream.read());

29 Chapter 929 Programming Example: Reading a File Name from the Keyboard, cont. class TextFileInputDemo2

30 Chapter 930 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.

31 Chapter 931 Opening a Binary File syntax ObjectOutputStream Output_Stream_Name = new ObjectOutputStream (new FileOutputStream(File_Name)); example ObjectOutputStream myOutputStream = new ObjectOutputStream (new FileOutputStream (“myfile.dat”));

32 Chapter 932 Output to Binary Files Using ObjectOutputStream class BinaryOutputDemo

33 Chapter 933 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

34 Chapter 934 Some Methods in Class ObjectOutputStream, cont. public void writeChar(int n) throws IOException public void writeBoolean(boolean b) throws IOException to write a String public void writeUTF(String aString) throws IOException

35 Chapter 935 Some Methods in Class ObjectOutputStream, cont. To write an object public void writeObject(Object anObject) throws IOException, NotSerializableException, InvalidClassException to close public void close() throws IOException

36 Chapter 936 Array Objects in Binary Files An entire array can be saved to a binary file using objectWrite, and can be read later using objectRead. If the base type of the array is a class, the class should be serializable. All the data in an array can be outputted to a binary file using a single invocation of objectWrite.

37 Chapter 937 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; } }

38 Chapter 938 Quiz Write a program that will write your name to a text file.


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

Similar presentations


Ads by Google