Java-Files & I/O and Exception

June 21,2016

Today i have learnt about the input-output stream and its use. Also i have learn about the exceptions i java and he to handle the exceptions.

Stream

A stream can be defined as a sequence of data. There are two kinds of Streams −

  • InPutStream − The InputStream is used to read data from a source.
  • OutPutStream − The OutputStream is used for writing data to a destination.

    streams

Reading and Writing Files

As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

file_io

FileInputStream

This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.

File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

FileOutputStream

FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn’t already exist, before opening it for output.

File f = new File(“C:/java/hello”); OutputStream f = new FileOutputStream(f);

Exception Handling

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

Exception Hierarchy

All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

exceptions1

 

Leave a comment