object-oriented design and programming (java). 2 topics covered today 3.1 input and output...

Click here to load reader

Upload: sarah-carson

Post on 17-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

  • Object-Oriented Design and Programming (Java)

  • Topics Covered Today3.1Input and Output Programming3.1.0 Java I/O Stream3.1.1File I/O3.1.2Using File I/O in the Library System

  • Java I/O StreamWhat is an I/O stream?Types of StreamsStream class hierarchyControl flow of an I/O operation using StreamsByte streamsCharacter streamsBuffered streamsStandard I/O streamsData streamsObject streamsFile class

  • What is an I/O Stream?An I/O Stream represents an input source or an output destinationA stream can represent many different kinds of sources and destinationsdisk files, devices, other programs, a network socket, and memory arraysStreams support many different kinds of datasimple bytes, primitive data types, localized characters, and objects

  • I/O StreamsNo matter how they work internally, all streams present the same simple model to programs that use themA stream is a sequence of data

  • Input StreamA program uses an input stream to read data from a source (a file, memory, a socket), and reads the information sequentially, one item at a time.

  • Output StreamA program uses an output stream to write data to a destination, and writing the information out sequentially, one item at time.

  • Types of StreamsGeneral Stream TypesCharacter and Byte StreamsCharacter vs. ByteInput and Output StreamsBased on source or destinationNode and Filter StreamsWhether the data on a stream is manipulated or transformed or not

  • Character and Byte StreamsByte streamsFor binary dataRoot classes for byte streams:The InputStream ClassThe OutputStream ClassBoth classes are abstractClasses of Byte Streams InputStreamOutputStreamFileInputStreamFileOutputStreamPipedInputStreamPipedOutputStreamByteArrayInputStreamByteArrayOutputStreamFilterInputStreamFilterOutputStreamDataInputStreamDataOutputStreamBufferedInputStreamBufferedOutputStream

  • Character and Byte StreamsCharacter StreamsFor Unicode charactersRoot classes for character streamsThe Reader classThe Writer classBoth classes are abstractMost programs should use readers and writers to read and write textual information. ReaderWriterInputStreamReaderOutputStreamWriterFileReaderFileWriterCharArrayReaderCharArrayWriterPipedReaderPipedWriterFilterReaderFilterWriterBufferedReaderBufferedWriterStringReaderStringWriter

  • Input and Output StreamsInput or source streamsCan read from these streamsRoot classes of all input streams:The InputStream ClassThe Reader Class

    Output or sink (destination) streamsCan write to these streamsRoot classes of all output streams:The OutputStream Class The Writer Class

  • Node and Filter StreamsNode streams (Data sink stream)Contain the basic functionality of reading or writing from a specific locationTypes of node streams include files, memory and pipesFilter streams (Processing stream)Layered onto node streams between threads or processesFor additional functionality- altering or managing data in the streamAdding layers to a node stream is called stream chaining (stream)

  • java.io hierarchies

  • Abstract ClassesInputStream & OutputStreamReader & Writer

  • InputStream Abstract ClassRead data from InputStream int read( ); Reads the next byte of data from the input streamint read( byte b[ ] ); Reads some number of bytes from the input stream and stores them into the buffer array b.int read( byte b[ ], int off, int len ); Reads up to len bytes of data from the input stream into an array of bytes.int available( ); Returns the number of bytes that can be read Close Streamclose( ); Closes this input stream and releases any system resources associated with the stream.

  • InputStream Abstract Class

  • Node InputStream Classes

  • Filter InputStream Classes

  • OutputStream Abstract ClassWrite data:void write( int b ); Writes the specified byte to this output stream.void write( byte b[ ] ); Writes b.length bytes from the specified byte array to this output streamvoid write( byte b[ ], int off, int len ); Writes len bytes from the specified byte array starting at offset off to this output stream.Close streamclose( ); Buffer flush:flush( ); Flushes this output stream and forces any buffered output bytes to be written out.

  • Node OutputStream Classes

  • Filter OutputStream Classes

  • The Reader ClassRead character(s)public int read() throws IOException; public int read(char cbuf[]) throws IOException; public abstract int read(char cbuf[],int off,int len) throws IOException;Close readerpublic abstract void close() throws IOException;

  • The Reader Class

  • Node Reader Classes

  • Filter Reader Classes

  • The Writer ClassWrite character(s) to output streampublic void write(int c) throws IOExceptionpublic void write(char cbuf[]) throws IOExceptionpublic abstract void write(char cbuf[],int off,int len) throws IOExceptionpublic void write(String str) throws IOExceptionpublic void write(String str,int off,int len) throws IOExceptionFlushflush( )Close streampublic abstract void close() throws IOException

  • Node Writer Classes

  • Filter Writer Classes

  • Control Flow of an I/O operation

  • Byte StreamPrograms use byte streams to perform input and output of 8-bit bytesAll byte stream classes are descended from InputStream and OutputStreamThere are many byte stream classesFileInputStream and FileOutputStream

  • When Not to Use Byte Streams?Byte Stream represents a kind of low-level I/O that you should avoidIf the data contains character data, the best approach is to use character streamsThere are also streams for more complicated data typesByte streams should only be used for the most primitive I/OAll other streams are based on byte stream

  • Example: FileInputStream & FileOutputStream

  • Example: FileInputStream & FileOutputStream

  • Character StreamThe Java platform stores character values using Unicode conventions

    Character stream I/O automatically translates this internal format to and from the local character set.In Western locales, the local character set is usually an 8-bit superset of ASCII.

    All character stream classes are descended from Reader and Writer

    As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter.

  • Example: FileReader & FileWriter

  • Example: FileReader & FileWriter

  • InputStreamReader & OutputStreamWriterpublic InputStreamReader(InputStream in);processing streamreads bytes from an InputStream and converts them to charactepublic InputStreamReader(InputStream in,String enc) throws UnsupportedEncodingException;charset decoderISO8859-1UTF-8UTF-16

    public OutputStreamWriter(OutputStream out); Processing streamconverts characters to bytes public OutputStreamWriter(OutputStream out,String enc) throws UnsupportedEncodingException;

  • Line-oriented I/O

  • Buffered StreamWhy Buffered Streams?An unbuffered I/O means each read or write request is handled directly by the underlying OSThis can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

    To reduce this kind of overhead, the Java platform implements buffered I/O streamsBuffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is emptySimilarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

  • How to create Buffered Streams?A program can convert a unbuffered stream into a buffered stream using the wrapping idiomA unbuffered stream object is passed to the constructor for a buffered stream classExample

    inputStream = new BufferedReader( new FileReader("xanadu.txt")); outputStream = new BufferedWriter( new FileWriter("characteroutput.txt"));

  • Buffered Stream ClassesBufferedInputStream and BufferedOutputStream create buffered byte streamsBufferedReader and BufferedWriter create buffered character streams

  • Flushing Buffered StreamsIt often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.Some buffered output classes support autoflush, specified by an optional constructor argument.When autoflush is enabled, certain key events cause the buffer to be flushedFor example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. To flush a stream manually, invoke its flush methodThe flush method is valid on any output stream, but has no effect unless the stream is buffered.

  • BufferedReader & BufferedWriterCreate buffered streampublic BufferedReader(Reader in); use the default buffer sizepublic BufferedReader(Reader in, int sz); public BufferedWriter(Writer out);public BufferedWriter(Writer out, int sz);BufferedReaderpublic String readLine() throws IOException; Read a line of textBufferedWriterpublic void newLine() throws IOException; Write a line separator.

  • Standard Streams on Java PlatformThree standard streamsStandard Input, accessed through System.inStandard Output, accessed through System.outStandard Error, accessed through System.err

    These objects are defined automatically and do not need to be openedSystem.out and System.err are defined as PrintStream objects

  • Data StreamsData streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values

    All data streams implement either the DataInput interface or the DataOutput interface

    DataInputStream and DataOutputStream are most widely-used implementations of these interfaces

  • DataOutputStreamDataOutputStream can only be created as a wrapper for an existing byte stream object

  • DataInputStreamLike DataOutputStream, DataInputStream must be constructed as a wrapper for a byte streamEnd-of-file condition is detected by catching EOFException, instead of testing for an invalid return value

  • Object Streams Object streams support I/O of objectsLike Data streams support I/O of primitive data typesThe object has to be Serializable type

    The object stream classes are ObjectInputStream and ObjectOutputStreamThese classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutputAn object stream can contain a mixture of primitive and object values

  • Input and Output of Complex ObjectThe writeObject and readObject methods are simple to use, but they contain some very sophisticated object management logicThis isn't important for a class like Calendar, which just encapsulates primitive values. But many object contain references to other objects.

    If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to.These additional objects might have their own references, and so on.

  • WriteObjectThe writeObject traverses the entire web of object references and writes all objects in that web onto the streamA single invocation of writeObject can cause a large number of objects to be written to the stream.

  • I/O of multiple referred-to objectsObject a contains references to objects b and c, while b contains references to d and e

  • Close StreamsAlways Close StreamsClosing a stream when it's no longer needed is very important so important that your program should use a finally block to guarantee that both streams will be closed even if an error occursThis practice helps avoid serious resource leaks.

  • Example: Closing File BufferedReader fileIn = new BufferedReader(new FileReader(filename));

    PrintWriter fileOut = new PrintWriter(new FileWriter(filename));...fileIn.close();fileOut.close();

  • Topics Covered Today3.1Input and Output Programming3.1.0 Java I/O Stream3.1.1File I/O3.1.2Using File I/O in the Library System

  • The java.io.File ClassEither a directory or a file

    Constructor:File(Stringpathname) File(Fileparent, Stringchild)File(Stringparent, Stringchild)

    File does not read and write, streams will handle the read or write from/to a file.

  • Create java.io.File ClassFile(Stringpathname)

    File(Fileparent, Stringchild)File(Stringparent, Stringchild)File Dir = new File(d:\\ssd3");File FullFilename = new File(Dir, "FileDemo.raw ");File f1 = new File("d:/ssd3/unit 3/DirList/.");File f2 = new File(".");

  • Listing Filesimport java.io.*;import java.util.*;public class DirList { public static void main(String[] args) { File path = new File("."); String[] list; System.out.println(path.getAbsolutePath()); list = path.list(); for (int i = 0; i < list.length; i++) System.out.println(list[i]); }}

  • Other File MethodscanRead()canWrite()exists()getParent()isDirectory()isFile()lastModified()length()

  • File Methods for ModifyingcreateNewFile()delete()makeDir()makeDirs()renameTo()setLastModified()setReadOnly()

  • FileInputStreamCreate a FileInputStreampublic FileInputStream(Stringname)public FileInputStream(Filefile)

    FileNotFoundException is thrown if the named file does not exist, it is a directory rather than a regular file, for some other reason cannot be opened for reading

    Closes this file input stream and releases any system resources associated with the stream

  • FileInputStream Exampleimport java.io.*;class MainClass { public static void main(String args[])throws Exception{ // 1. Create File object FileInputStream inFile=new FileInputStream("c:\\test.txt"); // 2. Create Reader Object to read the text BufferedReader reader=new BufferedReader( new InputStreamReader(inFile)); // 3. Read data String strLine; while((strLine=reader.readLine())!=null) System.out.println(strLine); reader.close(); inFile.close(); }}

  • FileOutputStreamCreate File Object

    Create FileOutputStream

    Write dataos.write(byte [ ] b)java.io.File file = new java.io.File("C:\\test.txt");java.io.OutputStream os = new java.io.FileOutputStream(file);

  • FileOutputStream Examplebyte[] Data = new byte[100]; java.io.File file = new java.io.File("C:\\test.txt ");try{ java.io.OutputStream os = new FileOutputStream(file); try { os.write(Data); } catch(java.io.IOException e) { }} catch (java.io.FileNotFound e) { }

  • FileReaderFileReader(Filefile) FileReader(StringfileName) // 1. Create Reader Object to read the text BufferedReader reader = new BufferedReader( new FileReader("c:\\test2.txt")); // 2. Read data line by line String strLine; while((strLine = reader.readLine()) != null) System.out.println(strLine); reader.close();

  • FileWriterAgain, basically the same. The constructors areFileWriter(File file)FileWriter(String fileName)FileWriter(String fileName, boolean append)

    The last one allows appending, rather than writing to the beginning (and erasing an existing file!).

    These will create files!

  • File I/O ExampleProgram description:It first prompts the user for two file names, the name of an input file and the name of an output file, and then copies the contents of the input file to the output file.

  • CopyFile.javaimport java.io.*;public class CopyFile {private static BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));

    private static PrintWriter stdOut = new PrintWriter( System.out, true);

    private static PrintWriter stdErr = new PrintWriter(System.err, true);

  • CopyFile.javapublic static void main(String[] args) throws IOException { stdErr.print("Source filename: "); stdErr.flush(); BufferedReader input = new BufferedReader( new FileReader(stdIn.readLine())); stdErr.print("Destination filename: "); stdErr.flush(); PrintWriter output = new PrintWriter(new FileWriter(stdIn.readLine()));

    String line = input.readLine(); while (line != null) { output.println(line); line = input.readLine(); } input.close(); output.close(); stdOut.println("done"); } }

  • Random-Access fileRandomAccessFile allow you to read/write data beginning at the a specified locationa file pointer is used to guide the starting positionit supports both input and output with both bytes and charactersMethods of Interface DataInput:readBoolean( ) readInt( ) readLine( ) Method of Interface DataOutput: writeChar( ) writeDouble( )

  • Using a Random Access Fileimport java.io.*;public class RAFDemo { public static void main(String[] args) { try { File f = new File(filename"); RandomAccessFile raf = new RandomAccessFile(f, "rw"); // Read a character char ch = raf.readChar();

    // Seek to end of file raf.seek(f.length()); // Append to the end raf.writeChars("aString"); raf.close(); } catch (IOException e) { } }}

  • File StreamThe file streams read or write from a file on the native file systemFile StreamsFileReaderFileWriterFileInputStreamFileOutputStream

  • Topics Covered Today3.1Input and Output Programming3.1.0 Java I/O Stream3.1.1File I/O3.1.2Using File I/O in the Library System

  • Add More FeaturesThe data for the library catalog will be stored in a data file and the library system will load the catalog from that file. catalog.dat

    The data formats are:Book_code_title_year_author_numberOfPages Recording_code_title_year_performer_format

    Borrower data will be write to a file in one of three formats: Plain text, HTML and XML.

  • UML class diagram

  • Interface LibraryCatalogLoader/** * This interface declares a method for obtaining a library catalog * from a file. */ public interface LibraryCatalogLoader { /** * Loads the information in the specified file into a library * catalog and returns the catalog. * * @param filename the name of the file that contains the catalog data. * @return a {@link Catalog}. * @throws FileNotFoundException if the specified file does not exist. * @throws IOException if there is an error reading the * information in the specified file. * @throws DataFormatException if the file contains malformed data. */ Catalog loadCatalog(String filename) throws IOException, FileNotFoundException, DataFormatException; }

  • Class FileLibraryCatalogLoader import java.util.*; import java.io.*; /** * Creates a library catalog and loads it with data stored in a file. * * @see Catalog * @see CatalogItem * @see Recording * @see Book */ public class FileLibraryCatalogLoader implements LibraryCatalogLoader { /* Prefix of a line with book data */ private final static String BOOK_PREFIX = "Book"; /* Prefix of a line with recording data */ private final static String RECORDING_PREFIX = "Recording"; /* Delimiter */ private final static String DELIM = "_";

  • Class FileLibraryCatalogLoader/** * Loads the information in the specified file into a library catalog and returns the catalog. * @param filename The name of a file that contains catalog information. * @return a library catalog. * @throws FileNotFoundException if the specified file does not exist. * @throws IOException if there is an error reading the information in the specified file. * @throws DataFormatException if the file contains malformed data. */ public Catalog loadCatalog (String filename) throws IOException, FileNotFoundException, DataFormatException { Catalog catalog = new Catalog(); BufferedReader reader = new BufferedReader(new FileReader(filename)); String line = reader.readLine(); while (line != null) { CatalogItem item = null; if (line.startsWith(BOOK_PREFIX)) { item = readBook(line); } else if (line.startsWith(RECORDING_PREFIX)) { item = readRecording(line); } else { throw new DataFormatException(line); } catalog.addItem(item); line = reader.readLine(); } return catalog; }

  • Class FileLibraryCatalogLoader/** * Extracts the book data in the specified line and returns * a {@link Book} object that encapsulates the book data. * * @param line a string that contains book data. * @return a Book object that encapsulates the * book data in the specified line. * @throws DataFormatException if the line contains errors. */ private Book readBook (String line) throws DataFormatException { StringTokenizer tokenizer = new StringTokenizer(line, DELIM); if (tokenizer.countTokens() != 6) { throw new DataFormatException(line); } else { try { String prefix = tokenizer.nextToken(); return new Book (tokenizer.nextToken(), tokenizer.nextToken(), Integer.parseInt(tokenizer.nextToken()), tokenizer.nextToken(), Integer.parseInt(tokenizer.nextToken())); } catch (NumberFormatException nfe) { throw new DataFormatException(line); } } }

  • Class FileLibraryCatalogLoader/** * Extracts the recording data in the specified line and returns * a {@link Recording} object that encapsulates the book data. * * @param line a string that contains recording data. * @return a Recording object that encapsulates the * recording data in the specified line. * @throws DataFormatException if the line contains errors. */ private Recording readRecording (String line) throws DataFormatException { StringTokenizer tokenizer = new StringTokenizer(line, DELIM); if (tokenizer.countTokens() != 6) { throw new DataFormatException(line); } else { try { String prefix = tokenizer.nextToken(); return new Recording (tokenizer.nextToken(), tokenizer.nextToken(), Integer.parseInt( tokenizer.nextToken()), tokenizer.nextToken(), tokenizer.nextToken()); } catch (NumberFormatException nfe) { throw new DataFormatException(line); } } } }

  • Class DataFormatException/** * This exception is thrown when malformed data is detected while * a file being parsed. */ public class DataFormatException extends Exception { /** * Constructs a DataFormatException with no detail message. */ public DataFormatException() { } /** * Constructs a DataFormatException with the * specified detail message. * * @param message the malformed data */ public DataFormatException(String message) { super(message); } }

  • Writing Data to a FileLibrarySystem.java

  • Complete Library SystemThe following files implement this version of the library system:Book.java Recording.java CatalogItem.java Catalog.java Borrower.java BorrowedItems.java BorrowerDatabase.java BorrowersFormatter.java PlainTextBorrowersFormatter.java HTMLBorrowersFormatter.java XMLBorrowersFormatter.java

    Character Streams;Byte Streams Node Streams(Filter Streams)/Invoking writeObject(a) writes not just a, but all the objects necessary to reconstitute a, so the other four objects in this web are written also; When a is read back by readObject, the other four objects are read back as well, and all the original object references are reserved.