Presentation is loading. Please wait.

Presentation is loading. Please wait.

Io package as Java’s basic I/O system cont’d Reading and Writing Files.

Similar presentations

Presentation on theme: "Io package as Java’s basic I/O system cont’d Reading and Writing Files."— Presentation transcript:

1 io package as Java’s basic I/O system cont’d Reading and Writing Files

2  Java provides a number of classes and methods that allow us to read and write files  In Java, all files are byte-oriented  Java provides methods to read and write bytes from and to a file  Java allows us to wrap a byte-oriented file-stream within a character based object  The two of most often-used stream classes are FileInputStream and FileOutputStream,  which create byte streams linked to files

3  To open a file, we simply create an object of one of the stream classes  by specifying the name of the file as an argument to the constructor  While FileInputStream and FileOutputStream classes support additional overriden constructors, we can write the followings: FileInputStream(String fileName) throws FileNotFoundException FileOutStream (String fileName) throws FileNotFoundException  fileName specifies the name of the file that we want to open  When we create an input stream, if the file does not exist, then FileNotFoundException is thrown  When an output file is opened, any preexisting file by the same name is destroyed.  When we use a file, you should close it calling close().  It is defined by both FileInputStream and FileOutputStream as follows: void close() throws IOException

4 Character Streams versus Byte Streams  The package provides classes that allow us to convert between Unicode character streams and byte streams of non-Unicode text.  With the InputStreamReader class, we can convert byte streams to character streams.  With the OutputStreamWriter class, we can translate character streams into byte streams.

5  Most of the functionality available for byte streams is also provided for character streams.  The methods for character streams generally accept parameters of data type char parameters, while byte streams work with byte data types.  The names of the methods in both sets of classes are almost identical except for the suffix,  Character-stream classes end with the suffix Reader or Writer and byte-stream classes end with the suffix InputStream and OutputStream.  For example, to read files using character streams, you would use the class; for reading it using byte streams you would use

6  When we create InputStreamReader and OutputStreamWriter objects,  We specify the byte encoding that we want to convert.  For example, to translate a text file in the UTF-8 encoding into Unicode, we create an InputStreamReader as follows: FileInputStream fis = new FileInputStream ("test.txt"); InputStreamReader isr = new InputStreamReader (fis, "UTF8");

7 Writing Files  To write a file, we use the write() method defined by FileOutSteam  Its the simplest form is shown here: void write (int byteval ) throwsIOException  This method writes the byte specified by byteval to the file.  Although byteval is declared as an integer, only low order eight bits are written to the file.

8 What is Unicode?  Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.  Computers just deal with numbers.  They store letters and other characters by assigning a number for each one.  Before Unicode was invented, there were hundreds of different encoding  No single encoding could contain enough characters:  The European Union alone requires several different encodings to cover all its languages.  Even for a single language like English no single encoding was adequate for all the letters, punctuation, and technical symbols in common use.

9 What is Unicode? con’t  These encoding systems also conflict with one another.  Two encodings can use the same number for two different characters, or use different numbers for the same character.  Any given computer (especially servers) needs to support many different encodings  Whenever data is passed between different encodings or platforms, that data always runs the risk of corruption.  Unicode is well on the way to replace ASCII, ISO 8859 and EUC at all levels

10 What is UTF-8?  UTF-8 stands for Unicode Transformation Format-8. It is an octet (8-bit) lossless encoding of Unicode characters.  With the UTF-8 encoding, Unicode can be used in a convenient and backwards compatible way in environments that, like Unix, were designed entirely around ASCII.  UTF-8 is the way in which Unicode is used under Unix, Linux, and similar systems. It is now time to make sure that you are well familiar with it and that your software supports UTF-8 smoothly.

11  To read from a file, we can use read() that is defined within FileInputStream. int read() throws IOException  Each time that it is called, it reads a single byte from the file, and returns byte as an integer value.  int read() returns an integer representation of the next available byte of input. -1 when the end of the file is encountered.  It can throw an IOException

12 Various Stream Classes  The package contains the Java I/O stream classes.  These classes are either the top level abstract classes or the specialized descendant implementation classes, both types are described below.  Top Level Classes : and  Reader and Writer are the abstract parent classes for character-stream based classes in the package.  The methods for reading and writing to streams found in these and their descendent classes are: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length)

13 /*This program uses read() to input and display the contents of a text file */ import*; class ShowFile { public static void main (String args[ ]) throws IOException { int i; FileInputStream fin; try { fin= new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.out.println ("File Not Found"); return; } catch (ArrayIndexOutOfBoundsException e ) { System.out.println ("Usage:Show File File"); return; } //read characters until EOF is encountered do {; if (i!=-1) System.out.print ((char) i); } while( i!= -1); fin.close(); }

14 Exception Handling Fundamentals  A Java exception is an object that describes an exception (that is error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused an error.  Java exception handling is managed via five keywords: try, catch, throw, throws, finally

15 General form of an exception- handling block try { // block code to monitor for errors } catch (Exception Type1 exOB) { //exception handler for ExceptionType1 } catch (ExceptionType2 exOB) { //exception handler for exceptionType2 } //.. finally { //block code to be executed before try block ends }

16 Execution Types  All exception types are subclass of the built-in-class Throwable  Throwable is at the top of the exception class hierarchy  Throwable has two subclasses that are partition exceptions:  Exception This class is used for exceptional conditions that user programs should catch An important subclass of exception called RuntimeException  Error Defines exceptions that are not caught under normal circumstances Exception types of error are used by the java run- time system to indicate errors having to do with the run-time environment

17 RuntimeException  public RuntimeException()  Constructs a RuntimeException with no detail message.  public RuntimeException ( String s) Constructs a RuntimeException with the specified detail message. Parameters: s - the detail message. java.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException

18 Uncaught Exceptions /*This program includes an expression that intentionally causes a divide by zero error*/ class A { public static void main (String args[]) { int d= 0; int a= 15/d; }  When Java runtime system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception  This causes A to stop

19 java.lang.ArithmeticException: /by zero at A.main( The class name A, the method name main, the filename, and the line number 6 in the simple stack tree The type of exception thrown is a subclass of Exception called ArithmeticException

20 Using try and catch class B { public static void main (String args[ ]) { int a,d; try { //monitor a block of code. d=0; a=43/d; System.out.println (“This will not be printed"); } catch (Arithmetic Exception e ) { //catch divide-by-zero error System.out.println (“After catch statement"); } This program generates the following output: After catch statement

21  The call to print() inside try block is never executed.  Once an exception is thrown, program control transfers out of the try block into the catch block Put differently,  catch is not “called”, so execution never “returns” to try block from a catch Thus  The line “This will not be printed” is not displayed  Once the catch statement is executed, program control continues with the next line in the program following the entire try/catch mechanism.

22  A try and its catch statement form a unit  The scope of the catch clause is restricted to those statements specified by the immediately proceeding try statement  A catch statement cannot catch an exception thrown by another try statement  The statements that are protected by try must be surrounded by curly braces.  We cannot use try on a single statement  The goal of most catch clauses should be to resolve the exceptional condition and then continue as if the error had never stopped.

23 Homework  Using Random() constructor (that creates a new random number generator) to obtain two random integers. (a and b)  Then divide two integers by each other (a/b)  The result value is used to divide the (12345/ (a/b)) Use try catch statements for the possibility of divide- by-zero error. Hint: use nextInt method to return the next pseudorandom, uniformly distributed int value from the random number generator's sequence. Here you have to use inheritance propery of random() class.

24 Class FileNotFoundException java.lang.Object java.lang.Throwable java.lang.Exception  This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.  It will also be thrown by these constructors if the file does exist but for some reason is inaccessible,  For example: when an attempt is made to open a read-only file for writing.

25 Class ArrayIndexOutOfBoundsException java.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException java.lang.IndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException  The object is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.  The constructor A rrayIndexOutOfBoundsException() constructs an ArrayIndexOutOfBoundsException with no detail message.

26 //copy a text file to the second file import*; class CopyFile { public static void main (String args[]) throws IOException { int i; FileInputStream fin; FileOutpurStream fout; try { //open input file try { fin = new FileInputStrem (args [0]); } catch (FileNotFoundException e) { System.out.println (“Input file not found”); return; } //open output file try { fout= new FileOutPutStream (args[1]); }

27 catch (FileNotFoundExcepton e) { System.out.println (“Error opening output File”); return; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println (“Usage: CopyFile from ….to……:”); return; } // copy File try { do {; if(i!=-1) fout.write(i); } while (i!= -1); } catch (IOException e) { System.out.println (“file error”); } fin.close(); fout.close(); }

Download ppt "Io package as Java’s basic I/O system cont’d Reading and Writing Files."

Similar presentations

Ads by Google