Full Transcript

Object-Oriented Programming with Java (OOPJ) DU # 2302CS304 Unit-5 Package, Exception Handling and IO Programming Prof. Pranami V. Sanja Department of Computer Engineering Darshan Institute o...

Object-Oriented Programming with Java (OOPJ) DU # 2302CS304 Unit-5 Package, Exception Handling and IO Programming Prof. Pranami V. Sanja Department of Computer Engineering Darshan Institute of Engineering & Technology for Diploma Studies, Darshan University, Rajkot [email protected] Topics  Looping Use of Package OOP Java is the easiest, scoring and my favorite subject CLASSPATH Access Control Exception and Error try, catch, throw, throws and finally Built in Exception Custom Exception File Class Byte Stream Character Stream OOP Java is the easiest, scoring and my favorite subject Package Section 1 Package  The package statement should be the first line in the source file.  There can be only one package statement in each source file. OOP Java is the easiest, scoring and my favorite subject  Package inside the package is called the sub-package.  Package can be categorized in two form: built-in package and user- defined package 1) built-in packages: Existing Java package such as java.lang, java.util, java.io, java.net, java.awt 2) User-defined-package : Java package created by user to categorized classes and interfaces. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 4 Package (Cont..) Example: class DemoPackage { package mypack; public static void main(String[] OOP Java is the easiest, scoring and my favorite subject class Book args) { { String bookname; Book b1 = new Book(); String author; b1.show(); Book() } { Compile: } javac -d. bookname = "Complete Reference";DemoPackage.java author = "Herbert"; Run : java mypack.DemoPackage } Output void show() Book name is :: Complete { Reference and author name is :: Herbert System.out.println("Book name is :: "+bookname + "\nand author name is :: "+ author); } } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 5 Package (Cont..) Import Package  import keyword is used to import built-in and user-defined packages into OOP Java is the easiest, scoring and my favorite subject your java source file.  If a class wants to use another class in the same package, no need to import the package.  A class file can contain any number of import statements.  There are three ways to access the package from outside the package: 1) import package.*;  If you use packagename.* then all the classes and interfaces of this package will be accessible but not sub-packages. 2) import package.classname;  If you use packagename.classname then only declared class of this package will be accessible. 3) fully qualified name  If you use fully qualified name then only class of package will be accessible. So, no #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO need Prof. toVimport Pranami Sanja package. 6 Package (Cont..) Import Package (Cont..) File 3: B.java Example: package pack; OOP Java is the easiest, scoring and my favorite subject File 1: A.java import pack.*; package pack; class B public class A { { public static void public void display() main(String args[]) { System.out.println("Welcome to package pack..."); { } A a1 = new A(); } a1.display(); File 2: Q.java pack.Q q1= new package pack; Output pack.Q(); public class Q java pack.B q1.Q_display(); { Welcome to package pack... } public void Q_display() } { Welcome to package pack through qualified name System.out.println("Welcome to package pack through qualified name..."); } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO } Prof. Pranami V Sanja 7 OOP Java is the easiest, scoring and my favorite subject CLASSPATH Section 2 CLASSPATH  CLASSPATH is an environment variable needed for the Java compiler and runtime to locate the Java packages/classes used in a Java program. OOP Java is the easiest, scoring and my favorite subject  CLASSPATH is similar to another environment variable PATH, which is used by the command shell to search for the executable programs.  CLASSPATH can be set by any of the following ways:  CLASSPATH can be set permanently in the environment.  CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command: SET CLASSPATH=“c:\tomcat\lib\servlet-api.jar”;  Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands. For example, java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 9 OOP Java is the easiest, scoring and my favorite subject Access Control Section 3 Access Control Visibility and Access Rights Access OOP Java is the easiest, scoring and my favorite subject AccessModifier Default Private Protected Public Location Same Class Yes Yes Yes Yes Subclass in Yes No Yes Yes Same Package Different Classes in Same Yes No Yes Yes Package Subclasses in Different No No Yes Yes Package Non-Subclasses in Different No No No Yes Package #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 11 OOP Java is the easiest, scoring and my favorite subject Exception and Error Section 4 Exception  An Exception is a problem that arises during the execution of a program.  When an exception occurs the normal flow of the program is disrupted OOP Java is the easiest, scoring and my favorite subject and the program/Application terminates abnormally, therefore these exceptions are needs to be handled.  The Exception Handling in java is one of the powerful mechanisms to handle the exception (runtime errors), so that normal flow of the application can be maintained.  When an exceptional event occurs in java, an exception is said to be thrown.  Exceptions are caused by users, programmers or when some physical resources get failed.  There are three categories of Exceptions: 1) Checked exceptions 2) Unchecked/Runtime exceptions 3) Errors #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 13 Exception (Cont..) 1)Checked Exceptions  Checked exceptions are checked at compile-time. OOP Java is the easiest, scoring and my favorite subject  It means if a method is throwing a checked exception then it should handle the exception using try-catch block or asserted in throws clause, otherwise the program will give a compilation error.  Example: IOException, SQLException 2) Unchecked/Runtime Exceptions  An Unchecked exception is an exception that occurs during the execution, also known as Runtime Exceptions.  It is ignored during compilation.  These exceptions occurs due to logic errors or improper data provided by user during execution.  Example: ArithmeticException, NullPointerException, ArrayIndexOutofBoundException 3) Errors  These are not exceptions, but problems that arise beyond the control of the user or the programmer. Prof. Pranami V Sanja #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO 14 Error  Error is an illegal operation performed by the user which results in the abnormal OOP Java is the easiest, scoring and my favorite subject working of the program.  Some of the errors inhibit the program from getting compiled or executed.  Thus errors should be removed before compiling and executing.  Errors can be classified as Compile time error, Run time error and Logical error. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 15 Types of Error  Compile time error:  Compile time errors are those errors which prevent the code from running. OOP Java is the easiest, scoring and my favorite subject  These errors are detected by the java compiler and an error message is displayed onto the screen while compiling.  Compile Time Errors are sometimes also referred to as Syntax errors.  For example : Misspelled variable name or method names, Missing semicolon, class not found.  Run time error:  Run Time errors occur or we can say, are detected during the execution of the program.  Sometimes these are discovered when the user enters an invalid data or data which is not relevant.  Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do.  During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) which detects it while the program is running.  For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error, Runtime Error caused by dividing #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 16 Types of Error (Cont..)  Logical error:  A logic error is when your program compiles and executes, but does the wrong thing OOP Java is the easiest, scoring and my favorite subject or returns an incorrect result or no output when it should be returning an output.  Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding.  Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning.  For example: If a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 17 OOP Java is the easiest, scoring and my favorite subject try, catch, throw, throws and finally Section 5 Exception Handling  Exception handling is done using five keywords:  try OOP Java is the easiest, scoring and my favorite subject  catch  finally  throw  throws #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 19 Exception Handling (Cont..) try block:  Java try block is used to enclose the code that might throw an exception. OOP Java is the easiest, scoring and my favorite subject  It must be used within the method.  Java try block must be followed by either catch or finally block. catch block:  Java catch block is used to handle the exception.  It must be used after the try block only.  The catch block that follows the try is checked, if the type of exception that occurred is listed in the catch block then the exception is handed over to the catch block that handles it.  You can use multiple catch block with a single try. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 20 Exception Handling (Cont..) Using try and catch Syntax: OOP Java is the easiest, scoring and my favorite subject try { //code might throw an exception If Exception generates } catch( ExceptionName1 e1) { Match with ExceptionName1 //Catch block 1 } catch( ExceptionName2 e2) { Match with ExceptionName2 //Catch block 2 } f not matched with ExceptionName1 or ExceptionName2 then program will stop & generate error message #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 21 Exception Handling (Cont..) Using try and catch Example: OOP Java is the easiest, scoring and my favorite subject Output class DemoTry { Divide by zero :: public static void main(String[java.lang.ArithmeticException: ] args) / by zero { Generate Exception, not try { possible to divide zero int arr[ ] = {1,2,3}; arr = 3/0; } catch( ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bound exception :: "+ e); } catch( ArithmeticException ae) { Match with ArithmeticException System.out.println("Divide by zero :: " + ae); } } } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 22 Exception Handling (Cont..) Using try and catch Nested try-catch blocks : OOP Java is the easiest, scoring and my favorite subject  try block within a try block is known as nested try block.  Nested try block is used when a part of a block may cause one error while entire block may cause another error.  if inner try block does not have a catch handler for a particular exception then the outer try is checked for match. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 23 Exception Handling (Cont..) Using try and catch When any exception generates in nested Syntax: try-catch first it checks for the nearest OOP Java is the easiest, scoring and my favorite subject try catch block for match. { If Exception Statement 1; This process continues until all catch generates try { block checked. //code might throw an exception } catch( ExceptionName e1) { Match with ExceptionName //Catch block1 } } catch( ExceptionName2 e2) Match with ExceptionName2 { //Catch block 2 } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 24 Exception Handling (Cont..) Using try and catch Example: OOP Java is the easiest, scoring and my favorite subject class DemoTry catch( ArithmeticException e) { { System.out.println("Divide by public static void main(String[ ] args) zero::"+ e); { } try catch(Exception e) { Generate { Exception, int arr[ ]={5,0,1,2}; System.out.println("Generic not try { exception :: "+ e); possible arr = arr/arr; } to divide } System.out.println("Out of try..catch zero catch( ArrayIndexOutOfBoundsException Outputae) block"); { Divide by zero :: } System.out.println("Array index out of } bound exception :: "+ ae); java.lang.ArithmeticException: / } zero } Out of try..catch block #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 25 Exception Handling (Cont..) finally  A finally keyword is used to create a block of code that follows a try or OOP Java is the easiest, scoring and my favorite subject catch block.  finally block of code always executes whether or not exception has occurred.  finally block appears at the end of catch block. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 26 Exception Handling (Cont..) finally Syntax: OOP Java is the easiest, scoring and my favorite subject try { // code might throw an exception } catch(ExceptionType1 e1) { //Catch block 1 } Whether any exception generates or not catch(ExceptionType2 e2) { finally block always executes. //Catch block 2 } finally { //The finally block always executes } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 27 Exception Handling (Cont..) finally  finally { a = 10; Example: OOP Java is the easiest, scoring and my favorite subject System.out.println("First element class DemoFinallyFinally always ecexutes { value: " +a); public static void main(String[ ] args) System.out.println("finally block is { always executed"); int a[ ] = new int;  try } { System.out.println("Out of System.out.println("Access element three :" + a); try..catch..finally"); }  catch( ArrayIndexOutOfBoundsException } ae) { } Output System.out.println("Exception :" Exception: + ae); } java.lang.ArrayIndexOutOfBoundsExc  eption: 3 First element value: 10 finally block is always executed Prof. Pranami V Sanja Out of try..catch..finally #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO 28 Exception Handling (Cont..) Summary of try…catch…finally  A catch clause cannot exist without a try statement. OOP Java is the easiest, scoring and my favorite subject  It is not compulsory to have finally clause for every try/catch.  The try block cannot be present without either catch clause or finally clause.  Code cannot be present in between the try, catch, finally blocks. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 29 Exception Handling (Cont..) throw  The throw keyword is used to explicitly throw an exception. OOP Java is the easiest, scoring and my favorite subject  We can throw either checked or uncheked exception using throw keyword.  Only object of Throwable class or its sub classes can be thrown.  Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax: Pass object of any checked throw ThrowableInstance; or unchecked exception Example: throw new ArithmeticException(); #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 30 Exception Handling throw Example: public static void main(String OOP Java is the easiest, scoring and my favorite subject class DemoThrow args[]) { {  static void demo() demo(); { } try { } Output  Exception caught: Demo throw new ArithmeticException(“Demo"); } catch(ArithmeticException ae) { System.out.println("Exception caught: “+ae); } } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 31 Exception Handling throws  The throws keyword is used to declare an exception. OOP Java is the easiest, scoring and my favorite subject  If a method does not handle a checked exception, the method must declare it using the throws keyword.  The throws keyword appears at the end of a method's signature.  You can declare multiple exceptions. Syntax: return_type method_name() throws exception_class_name_list { Pass list of exception name //method code separated by comma } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 32 Exception Handling (Cont..) Exception Handling Mechanism (Cont..) throws OOP Java is the easiest, scoring and my favorite subject Example: class DemoThrows {  catch(ArithmeticException static void display() throws ArithmeticException { ae)  System.out.println("Inside check function");{  int a = 10/0; System.out.println("Except } ion caught: “+ae); public static void main(String args[ ]) } { } Output } try Inside check function { display(); Exception caught:  } java.lang.ArithmeticException: / by zero #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 33 OOP Java is the easiest, scoring and my favorite subject Built in Exception Section 6 Java’s Inbuilt Unchecked Exceptions Exception Meaning OOP Java is the easiest, scoring and my favorite subject ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. StringIndexOutOfBounds Attempt to index outside the bounds of a string. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 35 Java’s Inbuilt Checked Exceptions Exception Meaning OOP Java is the easiest, scoring and my favorite subject ClassNotFoundException Class not found. IOException Input Output Exceptions CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 36 OOP Java is the easiest, scoring and my favorite subject Custom Exception Section 7 Custom Exception  We can create our own exception that is known as Custom exception or User-defined exception. OOP Java is the easiest, scoring and my favorite subject  We can have our own exception and message.  If you want to write a checked exception, you need to extend the Exception class.  If you want to write a runtime exception, you need to extend the RuntimeException class. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 38 Custom Exception (Cont..) class demoException Custom Exception or { User Defined Exception:  static void sum(int a,int b) throws OOP Java is the easiest, scoring and my favorite subject demoUserException Example: { class demoUserException extends Exception if(a < 0) { { throw new demoUserException (a); private int ex; } a = -10  demoUserException(int a) else { { System.out.println(a+b); ex = a; } } } public static void main(String[] args)  public String toString() { {  try { return "MyException[" + ex +"] sum(-10, 10); is less than zero"; } }  catch(demoUserException e) { System.out.println(e); } Output } MyException[-10] is less } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO than Prof. Pranami zero V Sanja } 39 OOP Java is the easiest, scoring and my favorite subject File Class Section 8 File Class  The File class from the java.io package, allow to work with files.  To use the File class, create an object of the class, and specify the OOP Java is the easiest, scoring and my favorite subject filename or directory name.  This class is used for creation of files and directories, file searching, file deletion etc.  Java File class represents the files and directory pathnames in an abstract manner.  The File object represents the actual file/directory on the disk. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 41 File Class (Cont..) Method Type Description canRead() Boolean Tests whether the file is readable OOP Java is the easiest, scoring and my favorite subject or not. canWrite() Boolean Tests whether the file is writable or not. createNewFile() Boolean Creates an empty file. delete() Boolean Deletes a file. exists() Boolean Test whether the file exists. getName() String Returns the name of file. getParent() String Returns the name of Parent directory. getAbsolutePath() String Returns absolute pathname of file. length() Long Returns size of file in bytes. list() String[] Returns an array of the files in the directory. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 42 File Class (Cont..) Example: (Creating a file) import java.io.File; catch (IOException e) { OOP Java is the easiest, scoring and my favorite subject import java.io.IOException; System.out.println("An error class Demo { occurred."); public static void main(String[] args) { try { e.printStackTrace(); } File myObj = new File("C:\\Users\\DELL\\Desktop\\filename.txt"); } if (myObj.createNewFile()) { } System.out.println("File created: " + myObj.getName()); Output: } File created: else { filename.txt System.out.println("File already exists."); } } #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 43 File Class (Cont..) Example: class FileDemo { System.out.println("File size: " + OOP Java is the easiest, scoring and my favorite subject f1.length() + " Bytes"); public static void main(String args[]) { } File f1 = new File("FileDemo.java"); } Output: System.out.println("File Name: " + f1.getName()); File Name: FileDemo.java System.out.println("Path: " + f1.getPath()); System.out.println("Abs Path: " + f1.getAbsolutePath()); Path: FileDemo.java System.out.println("Parent: " + f1.getParent()); System.out.println("exists: " + f1.exists()); Abs Path: C:\ System.out.println("canWrite: " + f1.canWrite());Users\DELL\Desktop\javap\ FileDemo.java System.out.println("canRead: " + f1.canRead()); Parent: null System.out.println("isDirectory: " + f1.isDirectory()); System.out.println("isFile: " + f1.isFile()); exists: true System.out.println("isAbsolute: " + f1.isAbsolute()); System.out.println("File last modified: " + f1.lastModified()); canWrite: true #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 44 OOP Java is the easiest, scoring and my favorite subject Stream Section 9 Stream  A stream is a sequence of data. In Java a stream is composed of bytes.  There are main two stream available InputStream and OutputStream. OOP Java is the easiest, scoring and my favorite subject  Based on they handle data, they are classified into ByteStream and CharacterStream.  In java, there are more 3 streams are represents input and output devices: 1) System.out - standard output stream 2) System.in - standard input stream 3) System.err - standard error stream #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 46 Byte Stream  Java byte streams are used to perform input and output of 8-bits / 1 byte at a time from binary file. OOP Java is the easiest, scoring and my favorite subject  InputStream and OutputStream class are most common used classes of byte stream. Stream class Description BufferedInputStream Used for Buffered input stream. BufferedOutputStream Used for Buffered output stream. DataInputStream Contains method for reading java standard data type. DataOutputStream Contains method for writing java standard data type. FileInputStream Input stream that reads from a file. FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output stream that contain print() and println() method. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 47 OOP Java is the easiest, scoring and my favorite subject FileOutputStream FileOutputStream  FileOutputStream is used to create a file and write data into it.  The FileOutputStream will only create a file, if it doesn't already exist, OOP Java is the easiest, scoring and my favorite subject before opening it for output.  There are two way for using file with FileOutputStream: 1) FileOutputStream f = new FileOutputStream("C:/java/hello.txt");  Here, directly File path is specified while creating the FileOutputStream object. 2) File f = new File("C:/java/hello.txt"); FileOutputStream f1 = new FileOutputStream( f );  First object of File is created and then FileOutputStream object is created and File object passed to the FileOutputStream as a argument. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 49 OOP Java is the easiest, scoring and my favorite subject FileInputStream FileInputStream  FileInputStream is used for reading data from the files.  While using FileInputStream class, file must already exist if file does not OOP Java is the easiest, scoring and my favorite subject exist it will generate error.  There are two way for using file with FileInputStream: 1) FileInputStream fin = new FileInputStream("C:/java/hello.txt");  Here, directly File path is specified while creating the FileInputStream object. 2) File f = new File("C:/java/hello.txt"); FileInputStream fin = new FileInputStream( f );  First object of File is created and then FileInputStream object is created and File object passed to the FileInputStream as a argument. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 51 FileOutputStream & FileInputStream Write a java program that writes the Hello.txt file into Hello1.txt using FileInputStream and FileOutputStream. OOP Java is the easiest, scoring and my favorite subject import java.io.*; catch (FileNotFoundException public class File_1 { { public static void main(String[] args) e.printStackTrace(); { } try { catch (IOException e) FileInputStream in = new { FileInputStream("C:/Hello.txt"); e.printStackTrace(); FileOutputStream out = new // handle exception FileOutputStream("C:/Hello1.txt"); } int c = 0; } while ((c = in.read()) != -1) } { out.write(c); } Output: in.close(); File Successfully Write out.close(); Prof. Pranami V Sanja #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO 52 OOP Java is the easiest, scoring and my favorite subject Character Stream Section-2 Character Stream  Character streams are used to perform input and output of 16-bits / 2 bytes at a time from Character file. OOP Java is the easiest, scoring and my favorite subject  Reader and Writer are most common used classes of character stream. Stream class Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character. OutputStreamReader Output stream that translate character to byte. Reader Abstract class that define character stream input. Writer Abstract class that define character stream output. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 54 OOP Java is the easiest, scoring and my favorite subject FileWriter FileWriter  Java FileWriter class is used to write character data to the file.  Two ways to create FileWriter Object. OOP Java is the easiest, scoring and my favorite subject 1. FileWriter f = new FileWriter(String fname); //File path is specified in argument. 2. FileWriter f = new FileWriter(File f1); //1st file is created and it is passed as argument. Method Description  Method for FileWriter Class: void write(int ch) Writing single character to the file. void write(String s) Writes the string into FileWriter. void write(char[] c) Writes char array into FileWriter. void close() Closes FileWriter. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 56 OOP Java is the easiest, scoring and my favorite subject FileReader FileReader  Java FileReader class is used to read character data from the file.  Two ways to create FileReader Object. OOP Java is the easiest, scoring and my favorite subject 1. FileReader f = new FileReader(String fname); //File path is specified in argument. 2. FileReader f = new FileReader(File f1); //1st file is created and it is passed as argument. Method Description  Method for FileReader Class: int read() Returns a character in ASCII form. It returns -1 at the end of file. int read(char[] ch) To read data from the file into char array. void close() Closes FileReader. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 58 FileReader & FileWriter Write a java program that writes the Hello.txt file into Hello1.txt using FileReader and FileWriter. OOP Java is the easiest, scoring and my favorite subject import java.io.*; System.out.println(“File public class File_1 Successfully Write"); { } public static void main(String[] args) throws } IOException { File f = new File ("C:/Hello.txt"); Output: File f1 = new File ("C:/Hello1.txt"); File Successfully Write FileReader fr = new FileReader(f); FileWriter fw = new FileWriter(f1); int c = 0; while ((c = fr.read()) != -1) { fw.write(c); } fr.close(); fw.close(); Prof. Pranami V Sanja #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO 59 OOP Java is the easiest, scoring and my favorite subject BufferedReader BufferedReader  BufferedReader class can be used to read data line by line using readLine() method. OOP Java is the easiest, scoring and my favorite subject BufferedOutputStream  BufferedOutputStream class uses an internal buffer to store data.  It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. BufferedInputStream  BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast. #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 61 BufferedReader (Cont..) Write a program in java that take character as a input from console and write it in file develop this program using Buffered Classes. OOP Java is the easiest, scoring and my favorite subject import java.io.*; br.close(); public class File_1 in.close(); { out.close(); public static void main(String[] args) throws } IOException catch { (IOException e) InputStreamReader in = new { InputStreamReader(System.in); e.printStackTra BufferedReader br = new BufferedReader(in); ce(); File f = new File ("C:/Hello.txt"); } try { } OutputStream out = new } Output: FileOutputStream(f); System.out.print("Type your text to write in file : "); Type your text to write in String str; file : str = br.readLine(); I like an ice byte b[ ] = str.getBytes(); cream #2302CS304(OOPJ) Unit 05 – Package, Exception Handling and IO Prof. Pranami V Sanja 62 Object Oriented Programming with JAVA (OOPJ) DU # 2302CS304 Thank You Prof. Pranami V Sanja Department of Computer Engineering Darshan Institute of Engineering and Technology for Diploma Studies, Rajkot. [email protected]. in

Use Quizgecko on...
Browser
Browser