1 Unit 8 (Basic Input/Output) Content A) Using files in JavaUsing files in Java B) Exception HandlingException Handling C) Filter StreamFilter Stream D)

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Files and Streams CS 21a. 10/02/05 L18: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Lecture 7 Exceptions and I/O. Overview of the exception hierarchy A simplified diagram of the exception hierarchy in Java Throwable ErrorException IOException.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CSC – Java Programming II Lecture 9 January 30, 2002.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
1 Exceptions Exception handling – Exception Indication of problem during execution – E.g., divide by zero – Chained exceptions Uses of exception handling.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
Java IO Exploring the java.io package and living to talk about it.
Keerthi Nelaturu Url: site.uottawa.ca/~knela006
Sequential files creation & writing
Lecture 8: I/O Streams types of I/O streams Chaining Streams
IO in java.
OO Design and Programming II I/O: Reading and Writing
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Lesson 8: More File I/O February 5, 2008
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Creating and Modifying Text part 2
File class File myFile=new File(“c:/javaDemo/aa
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
Web Design & Development Lecture 8
Exception Handling Contents
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

1 Unit 8 (Basic Input/Output) Content A) Using files in JavaUsing files in Java B) Exception HandlingException Handling C) Filter StreamFilter Stream D) The Standard Input & OutputThe Standard Input & Output

2 A) Using files in Java  The Java programming language provides no built-in facility for manipulating files. But the Java standard software library that comes with the JRE provides the necessary classes for performing such operations.  Most classes for performing I/O are in the java.io package. Hence you need to import it at the beginning of the source file import java.io.*;

3 File Object  Creating and using file objects: java.io.File class The File class enables you to get information/attributes about a file/directory  we cannot get access to the content/data of a file via a File object. It is not for that purpose!  Note that creating a File object will NOT create a physical file in your system.  The most common constructors for a File object: public File (String pathname) // full pathname of file public File (String parent, String child) // directory path + filename public File (File parent, String child) // directory object + filename

4  eg  Since the path separator in Windows is ‘\’, to prevent from confusion with special character in Java, e.g. ‘ \t ’, we add one more ‘\’ after ‘\’.  Creating a File instance does not create it physically on your computer drive. It can refer to a non-existing file and you can use the exists( ) method to determine whether the file exists or not. File myfile = new File (“file1”); // file1 in current directory File myfile = new File (“c:\\file2.txt”);// file2 in c:\file2.txt

5  A File instance can also be associated to a directory:  using the method list( ) to list the files in a directory File mydir = new File (“c:\\java\\MT201”); \\c:\java\MT201 String [ ] filename = mydir. list( ) ; for (int j=0;j<filename.length;j++) { System.out.println(filename[j]); }

6 file/directory operation method Method NameReturn Type public boolean canRead( )True if the file can be read, and false otherwise public boolean canWrite( )True if the file can be written, and false otherwise public boolean exists( )True if the file exists, and false otherwise public boolean isDirectory( )True if the name supplied to the constructor is referring to a physical file, and false otherwise public boolean isFile( )True if the name supplied to the constructor is referring to a physical file, and false otherwise public boolean isHidden( )True if the file is hidden, and false otherwise public long lastModified( )The time when the file is last modified and the time is specified in number of seconds since 00:00:00 GMT, Jan 1, 1970 public long length( )The size of the file

7 Reading and writing files  Reading a file can be viewed as a flow of data stream from the outside world into the JVM - input stream / source stream.  Writing a file can be viewed as a flow of data stream from the JVM to the outside world - output stream / destination stream.  In Java we can read / write data in units of 8-bit bytes or 16-bit Unicode characters. They are known as byte stream and character stream respectively  Byte stream is used for (byte-oriented) binary files, e.g. execution, image, audio, video files & etc  Character stream is used for (character-based) textual data, e.g. text files

8 Stream  Performing reading and writing operations on a file can be considered the flow of data between two entities.  For reading operation, a flow of data from the outside world into the JVM while for writing operation, a flow of data from the JVM to the outside world. Source Stream JVM Destination Stream Read / Input Operation Write / Output Operation

9 Table 8.4 different categories of stream classes  there are byte mode and character mode operations  1 byte = 8 bits  1 character = 2 byte = 16 its Byte stream (1 byte = 8 bits) Character stream (1 char = 2 byte = 16 bits) Input Stream InputStream  eg. FileInputStream Reader  eg. FileReader Output stream OutputStream  eg. FileOutputStream Writer  eg. FileWriter

10 Byte Stream  If an object supports a flow of data in units of byte, then it is known as a byte stream  it can be an input stream or output stream  byte stream is usually to handle binary file  The abstract class java.io.InputStream defines general types of how an input byte stream should behave  The abstract class java.io.OutputStream defines general types of how an output byte stream should behave  However, we have to use concrete subclasses of these abstract classes for us to manipulate a file  FileInputStream  FileOutputStream

11 FileOutputStream  Hence the steps to write to a file: 1.create an object of F ile O utput S tream class 2.send the write( ) messages to the FOS object 3.send the close( ) message to the FOS object  2 common ways to create a FileOutputStream object  method-a  method-b; one instruction is saved OutputStream out = new FileOutputStream( pathString ); File outFile = new File( pathString ); OutputStream out = new FileOutputStream( outFile );

12  Note that if the specified file already exists, creating an output stream onto that file will overwrite it.  So be careful and better check for file existence before writing it (modify method-a).  the write( ) method is overloaded in the OutputStream class: public void write(int b)// int but not byte ?! public void write(byte[] b) public void write(byte[] b, int offset, int length)// length = no of bytes

13 import java.io.*; public class TestFileOutput { public static void main(String args[]) { try { File myfile = new File (args[0]); FileOutputStream fs = new FileOutputStream (myfile); for (int j=0; j<100; j++) { fs.write (j); } fs.close ( ); } catch (Exception e) { } } example : FileOutputStream

14 Input Streams  The concept behind performing a reading operation is similar to the writing operation, but the direction of data flow is reversed.  The abstract InputStream class defines overloaded read( ) methods and close( ) method.  However if we want to read from a file, we must use of an object from the concrete FileInputStream class which is a subclass of the InputStream class  steps to read from a file: 1.create an object of FileInputStream class 2.send the read( ) messages to the FIS object until all data have been read from the source (indicated by a return value of -1 from the read( ) method) 3.send the close( ) message to the FIS object

15  2 most common ways to create a FileInputStream object:  runtime error occurs, if the file to be read does not exist  the read( ) method has been overloaded in the InputStream class:  Note that we could check whether we have read up to the end of a file by the condition: public int read( )// the byte data read is returned as int public int read(byte[] buf)// no. of bytes read is returned public int read(byte[] buf, int offset, int length)// no. of bytes read is returned InputStream fis = new FileInputStream( pathString );// method-B File inFile = new File( pathString );// method-A InputStream fis = new FileInputStream( inFile ); fis.read( ) == -1

16 example : FileInputStream import java.io.*; public class TestFileInput { public static void main(String args[]) { try { FileInputStream fs = new FileInputStream (args[0]); int i; while ((i = fs.read( ) ) != -1) { System.out.println(i); } fs.close( ) ; } catch (Exception e) { } }

17 Copying Data from InputStream to OutputStream import java.io.*; public class StreamCopier { public static void main(String args[]) { int i; try { FileInputStream ifs = new FileInputStream (args[0]); File myfile = new File (args[1]); FileOutputStream ofs = new FileOutputStream (myfile); while ((i = ifs.read( ) ) != -1 ) { ofs.write(i) ; } ifs.close( ) ; ofs.close( ) ; } catch (Exception e) { } }

18 Character Stream  Character stream is the character-based stream.  Every reading/writing operation handles the data in units of char.  It is usually used for handling textual data  The input character stream is generally considered a Reader object.  The output character stream is considered a Writer object.  Reader and Writer are abstract classes defining the common methods.  we’ll use concrete classes, FileReader and FileWriter for reading and writing files in units of character

19 FileWriter  2 most common ways to create a FileWriter object:  The overloaded write( ) method in the Writer class: Writer writer = new FileWriter( pathString );// method-B File outFile = new File( pathString );// method-A Writer writer = new FileWriter( outFile ); public void write(int c)// note int but not char type public void write(char[] c) public void write(char[] c, int offset, int length) public void write(String str) public void write(String str, int offset, int length)

20 example : FileWriter import java.io.*; public class TestFileWriter { public static void main(String args[]) { try { File myfile= new File (args[0]); FileWriter fw = new FileWriter ( myfile ); fw.write (1) ; fw.write( "Hello" ); fw.write( 'a' ); fw.close( ); } catch (Exception e) { } }

21 FileReader  the concept behind performing a reading operation is similar to the writing operation, but the direction of data flow is reversed.  If we want to read from a file, we need to make use of an object from the concrete FileReader class which is a subclass of the Reader class.  The steps to read from a file using an input character stream is similar to that of using an input byte stream  2 most common ways to create a FileReader object: Reader fr = new FileReader( pathString );// method-B File inFile = new File( pathString );// method-A Reader fr = new FileReader( inFile );

22  The overloaded read( ) method in the Reader class:  Note that we could check whether we have read up to the end of a file by the condition: public int read( )// the char data read is returned as int public int read(char[] buf)// no. of chars read is returned public int read(char[] buf, int offset, int length) fr. read( ) == -1

23 FileReader import java.io.*; public class TestFileReader { public static void main(String args[]) { int j; try { File myfile = new File (args[0]); FileReader fr = new FileReader (myfile); while ( ( j = fr.read( ) ) != -1) {// read Char ‘ j ’ System.out.println ((char) j );// casting } fr.close() } catch (Exception e) {} }

24 B) Exception Handling  An exception happens when a Java program performs an illegal operation, such as performing a division operation by zero at runtime.  Exception may also occur when a FileInputStream object refers to the non-existing file.  The occurrence of an exception indicates  a runtime error or  problematic situation.  The exception is generated to tell the program that such a problem has happened and the program should perform suitable remedial action to handle it.

25 Exception hierarchy Throwable ErrorException RuntimeExceptionIOException ArithmeticException unchecked exceptions checked exceptions … … … … FileNotFoundException

26  there are 2 handling approaches  throws // control is passed to the caller  try / catch / finally // to be resumed below the block  eg public class approach $2 throws Exception { } try { // codes that cause a potential checked exception } catch (Exception-class1 variable1) { // codes to execute in case of exception1 } catch (Exception-class2 variable2) { // codes to execute in case of exception2 } catch (…) {... } finally { // codes to execute no matter whether there is or isn’t exception }

27 Try/Catch  A program segment that can cause exceptions can be handled by using the keywords try and catch, eg : public class TestException { public static void main(String args[]) { int j=1; int a = Integer.parseInt(args[0]); try { j = j / a;// to be test for Division by zero } catch ( ArithmeticException e) { System.out.println(“error”); }

28  Multiple catch blocks are allowed in a program segment to catch different exceptions.  try / catch is required for some Java statements,  eg. when defining InputStream object;  otherwise compilation error occurs, eg.: TestFileOutput.java:7: unreported exception java.io. FileNotFoundException ; must be caught or declared to be thrown FileOutputStream fs = new FileOutputStream (myfile);

29  for multiple catch blocks, a checked exception is matched sequentially with the exception types specified. If the checked exception matches with the exception class or any of its subclasses, the corresponding codes inside the block is executed. Then execution is transferred to the finally block (if any) and the codes afterwards.  the following example is a bad catch blocks design. try { // codes that cause a potential checked exception } catch (IOException e) { // codes to execute in case of IOException } catch (FileNotFoundException e) { // codes to execute in case of FileNotFoundException }

30 Throwing Exception  Java allows a method that executes statements that may cause exceptions not to handle the caused exception by itself,  ie. no need to enclose those statements in a try/catch block.  We can use ‘throw ’ to stop running the subsequent statements in the method and the flow of the control will be returned to the caller method with the caused exception.  When an exception is raised in a method that throws it, execution in the method is terminated immediately and control is returned to the caller.  The caller (which is also inside a method) can again choose to handle the exception or throw the exception to its own caller.  Refer to the examples ByteStreamCopier.java and FileStreamCopy.java again. pp 67~68

31 C) Filter Stream  Java provides some classes that do not work on particular storage media or communication channels, but on the general input/output streams.  The idea is like this: Input filter input byte stream object  input stream filter object  data in JVM Output filter data in JVM  output stream filter object  output byte stream object  Java provides many filter classes for different purposes. The commonly used ones are for data conversion (e.g. converting bytes read into characters, integers and floating-point numbers), and improving performance (i.e. data buffering).

32 Filter streams for conversion  conversion between 8-bit byte and 16-bit character is the most common  Java handles characters in Unicode, which is a 16-bit coding system. but, characters in a text file in your storage can be 8 bits or 16 bits depending on the coding system of your platform (e.g. in Chinese Windows characters are represented in 8-bit ASCII code for English and 16-bit BIG5 code for Chinese).  Hence the same character can have different representations (codes) inside a text file on a particular platform and inside JVM.  And this is where translation/conversion is required when reading and writing character data between a data source and a data destination with JVM. char in data source  JVM (16-bit Unicode char)  char in data destination

33  the Reader and Writer classes introduced earlier are actually filter stream classes for data conversion.  the FileReader object creation is actually a shorthand of:  the FileWriter object creation is actually a shorthand of:  The conversion of an English letter from a text file (8-bit) to JVM (16-bit Unicode character) is simple. An extra byte filled with 0’s are added to the front of the 8-bit letter to make it 16-bit.  The reverse conversion of an English letter, i.e. from JVM to text file, is also simple. The first byte of the Unicode is taken away InputStream in = new FileInputStream(file);// byte stream Reader reader = new InputStreamReader(in);// character stream OutputStream out = new FileOutputStream(file);// byte stream Writer writer = new OutputStreamWriter(out);// character stream

34  However, if the conversion involves other non-ASCII characters (e.g. BIG5 Chinese character), we may have to specify explicitly the coding system in the filter’s constructors.  For example, you have a text file with Chinese BIG5 characters and you want to read it by a Java program running on a non-BIG5 platform. You have to specify the translation explicitly:  Refer to Unit 8 P.105 for details. public InputStreamReader(InputStream in, String charsetName); public OutputStreamWriter(OutputStream out, String charsetName); InputStream in = new FileInputStream(“myChineseFile.txt”); Reader reader = new InputStreamReader(in, “BIG5”);

35 Filter streams for buffering byte streams  reading and writing on physical files are slower than on memory  Instead of writing data byte-by-byte to physical file, it is better to write data temporarily to memory first and then a large block of data is transferred from memory to physical file. The temporarily memory is known as buffer.  The reverse is also true when reading data from physical file.  Data are pre-read in block into memory and released byte-by- byte upon request.  To achieve buffering transparently, we can make use of the BufferedInputSream and BufferedOutputStream classes. They are subclass of InputStream and OutputStream respectively.  Refer to the example BufferedStreamCopy.java.

36  Reading and writing files char-by-char are sometimes not preferable for text files, as it is slow and also we have to handle the line-break ourselves (which is different on different platforms).  Java provides some filter classes for us to read and write text files line-by-line.  We can wrap the BufferedReader object around the FileReader object to buffer the input character stream. The overloaded read( ) method reads a specified block of characters into the buffer. In addition, the readLine( ) method reads one complete line and returns a string. Reader reader = new FileReader(“myFile.txt”); BufferedReader br = new BufferedReader(reader); String lineRead = br.readLine( );

37  Similarly we can wrap the BufferedWriter object around the FileWriter object to buffer the output character stream.  The overloaded write( ) method writes a specified block of characters to the buffer  You have to flush( ) the output stream explicitly to ensure transfer of data from buffer to file.  However the class does not provide any method to write primitive data types as string to a text file.  We hence usually wrap another class PrintWriter around BufferedWriter to use the overloaded print( ) and println( ) methods. Writer writer = new FileWriter(“myFile.txt”); BufferedWriter bw = new BufferedWriter(writer); PrintWriter pw = new PrintWriter(bw); pw.println(100); pw.println(“Hello”); pw.println(999.99);

38 D) The Standard Input & Output  3 pre-defined standard I/O streams in java.lang. System :  System.in standard input  System.out standard output  System.err standard error  ‘ in ’, ‘ out ’ and ‘ err ’ are class variables of the class System.  The class variable ‘ in ’ refers to InputStream object  The class variable ‘ out & ‘ err ’ refer to PrintStream objects  When the JVM is launched, an InputStream object attached to the computer keyboard is prepared and is referred by the class variable ‘ in ’  Two PrintStream objects are prepared and are made accessible by class variables out and err

39  Since the class variable ‘ in ’ refers to the InputStream object that is attached to the keyboard and has the method read( ), keyboard entry can be read using :  To access the class variable ‘ in ’ and get the user inputs, we can type:  pp80 is an example of reading keystrokes from keyboard until the Ctrl-Z or Ctrl-D is pressed.  Since the class variable ‘ err ’ and ‘ out ’ refer to the PrintStream object which has a method print and method println, we can type: in. read( ) System.out.println(….) System.err.println(…..) System.out.print( ….) System.err.print(…..) System.in.read( )