Presentation is loading. Please wait.

Presentation is loading. Please wait.

7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.

Similar presentations


Presentation on theme: "7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing."— Presentation transcript:

1 7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing

2 7/2/2015CS2622 What I/O?  Basics first  Write output on the screen  Write output to a file  Get input from the command line  Get input from a file  Get input from the screen (swing)  As you can master the basics, move to advanced I/O

3 7/2/2015CS2623 File Class  abstraction  machine-independent  deals with most of the machine-dependent complexities of files and path names  filename is a string  Constructors  Methods: canRead(); canWrite(); exists(); isFile(); isAbsolute();

4 7/2/2015CS2624

5 7/2/2015CS2625 File Class Example  Examples\BJ_FileClassTest  http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html

6 7/2/2015CS2626 I/O Stream Similar to C/C++

7 7/2/2015CS2627 java.io package  Reading open a stream while more information read information read information close the stream  Writing open a stream while more information write information close the stream

8 7/2/2015CS2628 Character Streams and Byte Streams What is the difference?

9 7/2/2015CS2629 Superclass Reader (character)

10 7/2/2015CS26210 Superclass Reader (character)  Reader and Writer - abstract superclasses for character streams  Reader: API and partial implementation for readers Streams that read 16-bit characters Streams that read 16-bit characters Subclasses implement specialized streams Subclasses implement specialized streams  http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.ht ml http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.ht ml http://java.sun.com/j2se/1.5.0/docs/api/java/io/Reader.ht ml  Be familiar to searching specifications in the API documentation

11 7/2/2015CS26211 To read from a file  Use int read() int read( ) throws IOException int read( ) throws IOException  Reads a single character from the file and returns an integer value (0 to 65535)  Will block until a character is available, an I/O error occurs, or the end of the stream is reached.  Subclasses that intend to support efficient single- character input should override this method.  read( ) returns -1 when the EOF is encountered

12 7/2/2015CS26212 Superclass Writer (character) http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.htm

13 7/2/2015CS26213 Reader

14 7/2/2015CS26214 Writer

15 7/2/2015CS26215 FileReader To construct a FileReader, use the following constructors: public FileReader(String filename) public FileReader(File file) Ref: http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html A java.io.FileNotFoundException would occur if you attempt to create a FileReader with a nonexistent file.

16 7/2/2015CS26216 How to read with FileReader // Create an input stream input = new FileReader("temp.txt"); input = new FileReader("temp.txt"); int code; int code; /* Repeatedly read a character and display it on the console*/ /* Repeatedly read a character and 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);

17 7/2/2015CS26217 // 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(); }

18 7/2/2015CS26218 FileWriter http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileWriter.ht ml To construct a FileWriter, use the following constructors: public FileWriter(String filename) public FileWriter(String filename) public FileWriter(File file) public FileWriter(String filename, boolean append) public FileWriter(File file, boolean append)  See Examples\BJ_TestFileWriter.java

19 7/2/2015CS26219 InputStreamReader  InputStreamReader converts byte streams to character streams:  reads bytes and decodes them into characters using a specified charset. charset  charset specifiable by name by name or given explicitly, or given explicitly, or the platform's default charset or the platform's default charset

20 7/2/2015CS26220 Superclass Writer (character) http://java.sun.com/j2se/1.5.0/docs/api/java/io/Writer.htm

21 7/2/2015CS26221 InputStreamReader

22 7/2/2015CS26222 BufferedReader/BufferedWriter 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.

23 7/2/2015CS26223 Coding BufferedReader in = new BufferedReader(new FileReader("foo.in")); new BufferedReader(new FileReader("foo.in"));  buffers the input from the specified file.  Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient 

24 7/2/2015CS26224 Examples of BufferedReader  See BJ_BRread  BJ_BRreadLines  BJ_TinyEditor // reads multiple lines from console and reverberates using InputStreamReader and BufferedReader

25 7/2/2015CS26225 PrintWriter/PrintStream 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)

26 7/2/2015CS26226 PrintWriter To construct a PrintWriter: public PrintWriter(Writer out) public PrintWriter(Writer out, boolean autoFlush) If autoFlush is true, the println methods will cause the buffer to be flushed. The constructors and methods in PrintWriter and PrintStream do not throw an IOException. No need to invoke them from a try-catch block. Example: BJ_TestPrintWriter.java

27 7/2/2015CS26227 Binary I/O 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

28 7/2/2015CS26228 Superclass InputStream (byte)

29 7/2/2015CS26229 Superclass OutputStream (byte)

30 7/2/2015CS26230 Using the Streams Streams Type I/O PrintWriterPrintStreamPrinting FileReaderFileWriterFileInputStreamFileOutputStreamFile

31 7/2/2015CS26231 Open File for Reading File inFile = new File("test_in.txt"); FileReader in = new FileReader(inFile); File inFile = new File("test_in.txt"); FileInputStream in = new FileInputStream(inFile); 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

32 7/2/2015CS26232 FileReader vs. FileInputStream  FileReader reads streams of characters reads streams of characters  FileInputStream reads streams of raw bytes reads streams of raw bytes example: image dataexample: image data Can also read characters Can also read characters See BJ_ShowFile // reads from file and displaysSee BJ_ShowFile // reads from file and displays

33 7/2/2015CS26233 Open File for Writing File outFile = new File("test_out.txt"); FileWriter out = new FileWriter( outFile ); File outFile = new File("test_out.txt"); FileOutputStream out = new FileOutputStream(outFile); File outFile = new File(“test_out.txt”); PrintStream outfile = new PrintStream(outFile);

34 7/2/2015CS26234 Close File Infile.close( ); outFile.close( );

35 7/2/2015CS26235 Command Line Arguments 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 ”); System.out.println(“java command ”); }}

36 7/2/2015CS26236 Source Code Review and Demo Copy Files BJ_Copy_File CopyFileWOException andCopyfileWithException

37 7/2/2015CS26237 Combination of multiple input streams Source Code Review and Demo BJ_Concatenate Exercise : run Concatenate.java Don’t forget ListOfFiles.java Add a println statement to trace program execution and make sure you understand the execution sequence

38 Note the difference between  read() Return int Return int Check for -1 to detect EOF Check for -1 to detect EOF  readLine() Return a string Return a string Check for null to detect EOF Check for null to detect EOF 7/2/2015CS26238

39 7/2/2015CS26239 read( ) int c = in.read( ); int c; while( (c = in.read()) != -1 ) { …….}

40 7/2/2015CS26240 readLine( ) String str = infile.readLine( ); While( true ) { String str = infile.readLine( ); String str = infile.readLine( ); if( str == null ) break; if( str == null ) break; …… ……}


Download ppt "7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing."

Similar presentations


Ads by Google