7/2/2015cs2621 oo design and programming ii i/o: reading and writing

40
03/21/22 03/21/22 CS262 CS262 1 OO Design and OO Design and Programming II Programming II I/O: Reading and I/O: Reading and Writing Writing

Upload: tracey-campbell

Post on 21-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

04/19/2304/19/23 CS262CS262 11

OO Design and OO Design and Programming IIProgramming II

I/O: Reading and WritingI/O: Reading and Writing

04/19/2304/19/23 CS262CS262 22

What I/O?What I/O? Basics firstBasics first Write output on the screenWrite output on the screen Write output to a fileWrite output to a file Get input from the command lineGet input from the command line Get input from a fileGet input from a file Get input from the screen (swing)Get input from the screen (swing) As you can master the basics, move As you can master the basics, move

to advanced I/Oto advanced I/O

04/19/2304/19/23 CS262CS262 33

File ClassFile Class

abstraction abstraction machine-independentmachine-independent deals with most of the machine-dependent deals with most of the machine-dependent

complexities of files and path names complexities of files and path names filename is a stringfilename is a string ConstructorsConstructors Methods: canRead(); canWrite(); exists(); Methods: canRead(); canWrite(); exists();

isFile(); isAbsolute(); isFile(); isAbsolute();

04/19/2304/19/23 CS262CS262 44

java.io.File

+File(pathname: String)

+File(parent: String, child: String)

+File(parent: File, child: String)

+exists(): boolean

+canRead(): boolean

+canWrite(): boolean

+isDirectory(): boolean

+isFile(): boolean

+isAbsolute(): boolean

+isHidden(): boolean

+getAbsolutePath(): String

+getCanonicalPath(): String

+getName(): String

+getPath(): String

+getParent(): String

+lastModified(): long

+delete(): boolean

+renameTo(dest: File): Boolean

Creates a File object for the specified pathname. The pathname may be a directory or a file.

Creates a File object for the child under the directory parent. child may be a filename or a subdirectory.

Creates a File object for the child under the directory parent. parent is a File object. In the preceding constructor, the parent is a string.

Returns true if the file or the directory represented by the File object exists.

Returns true if the file represented by the File object exists and can be read.

Returns true if the file represented by the File object exists and can be written.

Returns true if the File object represents a directory.

Returns true if the File object represents a file.

Returns true if the File object is created using an absolute path name.

Returns true if the file represented in the File object is hidden. The exact definition of hidden is system-dependent. On Windows, you can mark a file hidden in the File Properties dialog box. On Unix systems, a file is hidden if its name begins with a period character '.'.

Returns the complete absolute file or directory name represented by the File object.

Returns the same as getAbsolutePath() except that it removes redundant names, such as "." and "..", from the pathname, resolves symbolic links (on Unix platforms), and converts drive letters to standard uppercase (on Win32 platforms).

Returns the last name of the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getName() returns test.dat.

Returns the complete directory and file name represented by the File object. For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.

Returns the complete parent directory of the current directory or the file represented by the File object. For example, new File("c:\\book\\test.dat").getParent() returns c:\book.

Returns the time that the file was last modified.

Deletes this file. The method returns true if the deletion succeeds.

Renames this file. The method returns true if the operation succeeds.

04/19/2304/19/23 CS262CS262 55

File Class ExampleFile Class Example

Examples\BJ_FileClassTestExamples\BJ_FileClassTest http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html

04/19/2304/19/23 CS262CS262 66

I/O StreamI/O Stream

Similar to C/C++

04/19/2304/19/23 CS262CS262 77

java.io packagejava.io package

ReadingReadingopen a streamopen a stream

while more informationwhile more information

read informationread information

close the streamclose the stream

WritingWritingopen a streamopen a stream

while more while more informationinformation

write informationwrite information

close the streamclose the stream

04/19/2304/19/23 CS262CS262 88

Character Streams and Character Streams and Byte StreamsByte Streams

What is the difference?

04/19/2304/19/23 CS262CS262 99

Superclass Reader Superclass Reader (character)(character)

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

04/19/2304/19/23 CS262CS262 1010

Superclass Reader Superclass Reader (character)(character)

Reader and Writer - abstract superclasses Reader and Writer - abstract superclasses for character streamsfor character streams

Reader: API and partial implementation for Reader: API and partial implementation for readersreaders Streams that read 16-bit charactersStreams that read 16-bit characters Subclasses implement specialized streamsSubclasses implement specialized streams

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.html Be familiar to searching specifications in the API Be familiar to searching specifications in the API

documentationdocumentation

04/19/2304/19/23 CS262CS262 1111

To read from a fileTo read from a file

Use int read()Use int read()

int read( ) throws IOExceptionint read( ) throws IOException Reads a single character from the file and returns an Reads a single character from the file and returns an

integer value (0 to 65535)integer value (0 to 65535) WillWill block block until a character is available, an I/O error until a character is available, an I/O error

occurs, or the end of the stream is reached. occurs, or the end of the stream is reached. Subclasses that intend to support efficient single-Subclasses that intend to support efficient single-

character input should override this method. character input should override this method. read( ) returns -1 when the EOF is encounteredread( ) returns -1 when the EOF is encountered

04/19/2304/19/23 CS262CS262 1212

Superclass Writer (character)Superclass Writer (character)

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.htm

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

04/19/2304/19/23 CS262CS262 1313

java.io.Reader

+read(): int

+read(cbuf: char[]): int

+read(cbuf: char[], off: int, len: int): int

+close(): void

+skip(n: long): long

+markSupported(): boolean

+mark(readlimit: int): void

+reset(): void

Reads the next character from the input stream. The value returned is an int in the range from 0 to 65535, which represents a Unicode character. Returns -1 at the end of the stream.

Reads characters from the input stream into an array. Returns the actual number of characters read. Returns -1 at the end of the stream.

Reads characters from the input stream and stores into cbuf[off], cbuf[off+1], …, cbuf[off+len-1]. The actual number of bytes read is returned. Returns -1 at the end of the stream.

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

Skips over and discards n characters of data from this input stream. The actual number of characters skipped is returned.

Tests if this input stream supports the mark and reset methods.

Marks the current position in this input stream.

Repositions this stream to the position at the time the mark method was last called on this input stream.

Reader

04/19/2304/19/23 CS262CS262 1414

java.io.Writer

+write(int c): void

+write(cbuf: byte[]): void

+write(cbuf: char[], off: int, len: int): void

+write(str: String): void

+write(str: String, off: int, len: int): void

+close(): void

+flush(): void

Writes the specified character to this output stream. The parameter c is an int value. (char)c is written to the output stream.

Writes all the characters in array cbuf to the output stream.

Writes cbuf[off], cbuf[off+1], …, cbuf[off+len-1] into the output stream.

Writes the characters from the string into the output stream.

Writes a portion of the string characters into the output stream.

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

Flushes this output stream and forces any buffered output characters to be written out.

Writer

04/19/2304/19/23 CS262CS262 1515

FileReaderFileReader

To construct a FileReader, use the following To construct a FileReader, use the following constructors:constructors:public FileReader(String filename)public FileReader(String filename)

public FileReader(File file)public FileReader(File file)

Ref: Ref: http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html

A A java.io.FileNotFoundExceptionjava.io.FileNotFoundException would occur if would occur if you attempt to create a you attempt to create a FileReaderFileReader with a with a nonexistent file. nonexistent file.

04/19/2304/19/23 CS262CS262 1616

How to read with FileReaderHow to read with FileReader

// Create an input stream// Create an input stream input = new FileReader("temp.txt");input = new FileReader("temp.txt");

int code;int code; /* Repeatedly read a character and /* Repeatedly read a character and

display it on the console*/display it on the console*/ while ((code = input.read()) != -1)while ((code = input.read()) != -1) System.out.print((char)code);System.out.print((char)code);

04/19/2304/19/23 CS262CS262 1717

// To catch I/O exceptions try { // Create an input stream // Repeatedly read a character and display it on the console } catch (FileNotFoundException ex) { System.out.println("File temp.txt does not exist"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } }

04/19/2304/19/23 CS262CS262 1818

FileWriterFileWriter

http://java.sun.com/j2se/1.5.0/docs/api/java/io/http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileWriter.htmlFileWriter.html

To construct a FileWriter, use the following To construct a FileWriter, use the following constructors:constructors:

public FileWriter(String filename)public FileWriter(String filename)

public FileWriter(File file)public FileWriter(File file)

public FileWriter(String filename, boolean public FileWriter(String filename, boolean appendappend))

public FileWriter(File file, boolean append)public FileWriter(File file, boolean append)

See Examples\BJ_TestFileWriter.javaSee Examples\BJ_TestFileWriter.java

04/19/2304/19/23 CS262CS262 1919

InputStreamReaderInputStreamReader

InputStreamReader converts byte streams InputStreamReader converts byte streams to character streams: to character streams:

reads bytes and decodes them into reads bytes and decodes them into characters using a specified charset. characters using a specified charset.

charset specifiable charset specifiable by name by name or given explicitly, or given explicitly, or the platform's default charsetor the platform's default charset

04/19/2304/19/23 CS262CS262 2020

Superclass Writer (character)Superclass Writer (character)

http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.htm

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

04/19/2304/19/23 CS262CS262 2121

Program

The Unicode of the character is returned

A character is converted into the Unicode

The Unicode of the character is sent out

A character stored in a specified encoding

A character is converted into the code for the specified encoding

InputStreamReaderInputStreamReader

04/19/2304/19/23 CS262CS262 2222

BufferedReader/BufferedWriterBufferedReader/BufferedWriter

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

For efficient I/O:BufferedReader: readLine() method If the end of stream is reached, readLine() returns null.

BufferedWriter: newLine() method to write a line separator.

04/19/2304/19/23 CS262CS262 2323

CodingCoding

BufferedReader in = BufferedReader in =

new BufferedReader(new FileReader("foo.in")); new BufferedReader(new FileReader("foo.in")); buffers the input from the specified file. buffers the input from the specified file. Without buffering, Without buffering,

each invocation of read() or readLine() could cause each invocation of read() or readLine() could cause bytes to be read from the file, converted into bytes to be read from the file, converted into characters, and then returned, which can be very characters, and then returned, which can be very inefficientinefficient

04/19/2304/19/23 CS262CS262 2424

Examples of BufferedReaderExamples of BufferedReader

See BJ_BRreadSee BJ_BRread BJ_BRreadLinesBJ_BRreadLines BJ_TinyEditor // reads multiple lines from BJ_TinyEditor // reads multiple lines from

console and reverberates using console and reverberates using InputStreamReader and BufferedReaderInputStreamReader and BufferedReader

04/19/2304/19/23 CS262CS262 2525

PrintWriter/PrintStreamPrintWriter/PrintStream

Reader

Writer

Object

PrintWriter

BufferedWriter

FileReader

FileWriter

InputStreamReader

BufferedReader

OutputStreamWriter

BufferedWriter: outputs characters and strings. PrintWriter and PrintStream both output objects, strings and numeric values as text.

PrintWriter in jdk1.2 and more efficient

replaces PrintStream jdk1.0)

04/19/2304/19/23 CS262CS262 2626

PrintWriterPrintWriterTo construct a PrintWriter:To construct a PrintWriter:

public PrintWriter(Writer out)public PrintWriter(Writer out)public PrintWriter(Writer out, boolean autoFlush)public PrintWriter(Writer out, boolean autoFlush)

  If autoFlush is true, the println methods will cause the buffer If autoFlush is true, the println methods will cause the buffer

to be flushed.to be flushed.

The constructors and methods in The constructors and methods in PrintWriterPrintWriter and and PrintStreamPrintStream do not throw an do not throw an IOExceptionIOException. .

No need to invoke them from a No need to invoke them from a try-catchtry-catch block. block.

Example: BJ_TestPrintWriter.javaExample: BJ_TestPrintWriter.java

04/19/2304/19/23 CS262CS262 2727

Binary I/OBinary I/O

Text I/O

The Unicode of the character

Encoding/ Decoding

The encoding of the character is stored in the file

Binary I/O

A byte is read/written

The same byte in the file

Text I/O: read: specific encoding to Unicode

write: Unicode to file specific encoding

Binary I/O: No conversions;

exact byte read or written to file

04/19/2304/19/23 CS262CS262 2828

Superclass InputStream Superclass InputStream (byte)(byte)

04/19/2304/19/23 CS262CS262 2929

Superclass OutputStream Superclass OutputStream (byte)(byte)

04/19/2304/19/23 CS262CS262 3030

Using the StreamsUsing the StreamsStreamsStreamsType I/OType I/O

PrintWriterPrintWriter

PrintStreamPrintStream

PrintingPrinting

FileReaderFileReader

FileWriterFileWriter

FileInputStreamFileInputStream

FileOutputStreamFileOutputStream

FileFile

04/19/2304/19/23 CS262CS262 3131

Open File for ReadingOpen File for Reading

File inFile = new File("test_in.txt");File inFile = new File("test_in.txt");

FileReader in = new FileReader(inFile);FileReader in = new FileReader(inFile);

File inFile = new File("test_in.txt");File inFile = new File("test_in.txt");FileInputStream in = new FileInputStream(inFile);FileInputStream in = new FileInputStream(inFile);

Q: What is the difference?Q: What is the difference?http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileInputStream.html

http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html

04/19/2304/19/23 CS262CS262 3232

FileReader vsFileReader vs. . FileInputStreamFileInputStream

FileReaderFileReader reads streams of charactersreads streams of characters

FFileInputStreamileInputStream reads streams of raw bytes reads streams of raw bytes

• example: image dataexample: image data Can also read charactersCan also read characters

• See BJ_ShowFile // reads from file and displaysSee BJ_ShowFile // reads from file and displays

04/19/2304/19/23 CS262CS262 3333

Open File for WritingOpen File for Writing

File outFile = new File("test_out.txt");File outFile = new File("test_out.txt");FileWriter out = new FileWriter( outFile );FileWriter out = new FileWriter( outFile );

File outFile = new File("test_out.txt");File outFile = new File("test_out.txt");FileOutputStream out = new FileOutputStream(outFile);FileOutputStream out = new FileOutputStream(outFile);

File outFile = new File(“test_out.txt”);File outFile = new File(“test_out.txt”);PrintStream outfile = new PrintStream(outFile);PrintStream outfile = new PrintStream(outFile);

04/19/2304/19/23 CS262CS262 3434

Close FileClose File

Infile.close( );Infile.close( );

outFile.close( );outFile.close( );

04/19/2304/19/23 CS262CS262 3535

Command Line ArgumentsCommand Line Arguments

public static void main(String[ ] args) {public static void main(String[ ] args) {

if( args.length == 2 ) { if( args.length == 2 ) { String firstArgument = args[0];String firstArgument = args[0]; String secondArgument = args[1];String secondArgument = args[1]; } else {} else { System.out.println(“java command <args1> <args2>”);System.out.println(“java command <args1> <args2>”); }}}}

04/19/2304/19/23 CS262CS262 3636

Source Code ReviewSource Code Reviewand Demoand DemoCopy FilesCopy Files

BJ_Copy_FileBJ_Copy_File

CopyFileWOException CopyFileWOException andCopyfileWithExceptionandCopyfileWithException

04/19/2304/19/23 CS262CS262 3737

Combination of multiple Combination of multiple input streamsinput streams

Source Code Review and DemoSource Code Review and Demo

BJ_ConcatenateBJ_ConcatenateExercise : run Concatenate.javaExercise : run Concatenate.java

Don’t forget ListOfFiles.javaDon’t forget ListOfFiles.java

Add a println statement to trace program execution and Add a println statement to trace program execution and

make sure you understand the execution sequencemake sure you understand the execution sequence

Note the difference betweenNote the difference between

read()read() Return intReturn int Check for -1 to detect EOFCheck for -1 to detect EOF

readLine()readLine() Return a stringReturn a string Check for null to detect EOFCheck for null to detect EOF

04/19/2304/19/23 CS262CS262 3838

04/19/2304/19/23 CS262CS262 3939

read( ) read( )

int c = in.read( );int c = in.read( );

int c;int c;

while( (c = in.read()) != -1 ) {while( (c = in.read()) != -1 ) {

…………..

}}

04/19/2304/19/23 CS262CS262 4040

readLine( ) readLine( )

String str = infile.readLine( );String str = infile.readLine( );

While( true ) {While( true ) {

String str = infile.readLine( );String str = infile.readLine( );

if( str == null ) break;if( str == null ) break;

…… ……

}}