0% found this document useful (0 votes)
11 views32 pages

Java Unit 3

The document covers Exception Handling and File I/O Streams in Java, detailing the types of exceptions, their advantages, and the keywords used for handling them such as try, catch, throw, and finally. It explains the difference between errors and exceptions, provides examples of common exceptions, and discusses the importance of maintaining the normal flow of application execution. Additionally, it includes syntax examples and scenarios for using exception handling effectively.

Uploaded by

godwinraj2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views32 pages

Java Unit 3

The document covers Exception Handling and File I/O Streams in Java, detailing the types of exceptions, their advantages, and the keywords used for handling them such as try, catch, throw, and finally. It explains the difference between errors and exceptions, provides examples of common exceptions, and discusses the importance of maintaining the normal flow of application execution. Additionally, it includes syntax examples and scenarios for using exception handling effectively.

Uploaded by

godwinraj2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

JAVA PROGRAMMING

UNIT III EXCEPTION AND FILE I/O STREAMS

Exceptions-benefits of exception-Types of Exceptions-Errors-Control flow- JVM reaction


to Exception usage of try, catch, throw, final and finally keyword-rethrowing exceptions,
exception specification, built in exceptions-File I/O: Standard Streams-Reading and
writing Streams- Byte Array Stream-Data Stream- File Stream- Input and output Stream.

Exception:
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors
so that the normal flow of the application can be maintained.

What is Exception in Java?


Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the
rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of the statements will be executed. That is why we
use exception handling in Java.

The advantages of Exception Handling in Java


 Provision to Complete Program Execution.
 Easy Identification of Program Code and Error-Handling Code.
 Propagation of Errors.
 Meaningful Error Reporting.
 Identifying Error Types.

Difference between error and exception

Errors indicate serious problems and abnormal conditions that most applications should not try
to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example, memory error, hardware error, JVM error etc.
Exceptions
are conditions within the code. A developer can handle such conditions and take necessary
corrective actions. Few examples

DivideByZeroException
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
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. If an exception is raised, which has not been handled by
programmer then program execution can get terminated and system prints a non-user-friendly
error message.
Ex: Exception in thread "main" java.lang.ArithmeticException: / by
zero at ExceptionDemo.main(ExceptionDemo.java:5)
Where, ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
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.

Key words used in Exception handling

There are 5 keywords used in java exception handling.

1. try A try/catch block is placed around the code that might generate an exception. Code
within a try/catch block is referred to as protected code.
2. catch A catch statement involves declaring the type of exception we are trying to catch.

3. finally A finally block of code always executes, irrespective of occurrence of an Exception.

4. throw It is used to execute important code such as closing connection, stream etc. Throw is
used to invoke an exception explicitly.
5. throws throws are used to postpone the handling of a checked exception.

Syntax : //Example-predefined Excetion - for


Try //ArrayindexoutofBounds Exception
{ public class ExcepTest
//Protected code {
} public static void main(String args[])
{ int a[] = new int[2];
catch(ExceptionType1 e1) try
{ { System.out.println("Access element three :" + a[3]);
//Catch block }
} catch(ArrayIndexOutOfBoundsException e)
catch(ExceptionType2 e2) { System.out.println("Exception thrown :" + e);
{ }
//Catch block finally
} { a[0] = 6;
catch(ExceptionType3 e3) System.out.println("First element value: " + a[0]);
{ System.out.println("The finally statement is executed");
//Catch block }
} }
Finally }
{ Output
Exception
//The finally block always thrown :java.lang.ArrayIndexOutOfBoundsException:3
executes. First element value: 6
} The finally statement is executed
Note : here array size is 2 but we are trying to access 3rd
element.
Uncaught Exceptions

This small program includes an expression that intentionally causes a divide-by-zero error: class
Exc0 {public static void main (String args []) {int d = 0; int a = 42 / d;} } When the Java run-
time system detects the attempt to divide by zero, it constructs a new exception object and then
throws this exception. This causes the execution of Exc0 to stop, because once an exception has
been thrown, it must be caught by an exception handler and dealt with immediately

Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program. Here is the exception
generated when this example is executed:

java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)

Stack Trace:

Stack Trace is a list of method calls from the point when the application was started to the point
where the exception was thrown. The most recent method calls are at the top. A stack trace is a
very helpful debugging tool. It is a list of the method calls that the application was in the middle
of when an Exception was thrown. This is very useful because it doesn't only show you where
the error happened, but also how the program ended up in that place of the code.
Using try and Catch

To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. A try and its catch statement form a unit. The following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:

Example:
class Exc2 {
public static void main (String args []) {
int d, a;
try {// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

Output:
Division by zero.
After catch statement.

The call to println () inside the try block is never executed. Once an exception is thrown,
program control transfers out of the try block into the catch block.

Multiple catch Clauses

In some cases, more than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different type of
exception. When an exception is thrown, each catch statement is inspected in order, and the first
one whose type matches that of the exception is executed. After one catch statement executes,
the others are bypassed, and execution continues after the try/catch block.

Example:
The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output:
Here is the output generated by running it both ways:
C:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack. If an
inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match. This continues until one of
the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch
statement matches, then the Java run-time system will handle the exception.

Example:
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output:
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds: java. lang. ArrayIndexOutOfBoundsException:42

Throw

it is possible for your program to throw an exception explicitly, using the throw statement.
Syntax:
throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object,
cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a
parameter in a catch clause, or creating one with the new operator.

The flow of execution stops immediately after the throw statement; any subsequent statements
are not executed. The nearest enclosing try block is inspected to see if it has a catch statement
that matches the type of exception. If it does find a match, control is transferred to that statement.
If not, then the next enclosing try statement is inspected, and so on. If no matching catch is
found, then the default exception handler halts the program and prints the stack trace.

Example:
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

Output:
Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

Throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this
by including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw. This is necessary for all exceptions, except those of type
Error or RuntimeException, or any of their subclasses. All other exceptions that a method can
throw must be declared in the throws clause.
Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw
Example:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output:
inside throwOne
caught java.lang.IllegalAccessException: demo

finally
The finally keyword is designed to address this contingency. finally creates a block of code that
will be executed after a try/catch block has completed and before the code following the
try/catch block. The finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement matches the
exception. Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just before
the method returns. This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional.
Example:
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
Output:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally

Types of Exceptions
 Checked exceptions − A checked exception is an exception that occurs at the compile
time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored at the time of compilation, the programmer should take care of (handle) these
exceptions.
 Unchecked exceptions − An unchecked exception is an exception that occurs at the
time of execution. These are also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API. Runtime exceptions
are ignored at the time of compilation.

 Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, Assertion Error etc.

Common scenarios where exceptions may occur:


There are given some scenarios where unchecked exceptions can occur. They are as
follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) Scenario where NullPointerException occurs


If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would
result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Java’s Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are
suitable to explain certain error situations.

Examples of Built-in Exception:


1. Arithmetic exception: It is thrown when an exceptional condition has occurred in an
arithmetic operation.
/ Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}

Output:
Can't divide a number by 0

2. ArrayIndexOutOfBounds Exception : It 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.

// Java program to demonstrate


// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:

Array Index is Out Of Bounds

3. ClassNotFoundException : This Exception is raised when we try to access a class whose


definition is not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal {

} class Geeks {

} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
Output:

ClassNotFoundException

4. FileNotFoundException: This Exception is raised when a file is not accessible or does not
open.

// Java program to demonstrate


// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[])


{
try {

// Following file does not exist


File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);


}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:

File does not exist

5. IOException : It is thrown when an input-output operation failed or interrupted

// Java program to illustrate IOException


import java.io.*;
class Geeks {
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
}

}
Output:

error: unreported exception IOException; must be caught or declared to be thrown

6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some


processing, and it is interrupted.
// Java Program to illustrate
// InterruptedException
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:

error: unreported exception InterruptedException; must be caught or declared to be thrown

7. NoSuchMethodException : t is thrown when accessing a method which is not found.

// Java Program to illustrate


// NoSuchMethodException
class Geeks {
public Geeks()
{
Class i;
try {
i = Class.forName("java.lang.String");
try {
Class[] p = new Class[5];
}
catch (SecurityException e) {
e.printStackTrace();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String[] args)


{
new Geeks();
}
}
Output:

error: exception NoSuchMethodException is never thrown in body of corresponding try


statement

8. NullPointerException : This exception is raised when referring to the members of a null


object. Null represents nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

Output:

NullPointerException.

9. NumberFormatException : This exception is raised when a method could not convert a


string into a numeric format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo {
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt("akki");

System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:

Number format exception

10. ClassCastException

/ Java Program to illustrate


// ClassCastException
class Test {
public static void main(String[] args)
{
String s = new String("Geeks");
Object o = (Object)s;
Object o1 = new Object();
String s1 = (String)o1;
}
}

Output:

Exception in thread "main" java.lang.ClassCastException:


java.lang.Object cannot be cast to java.lang.String

User-defined Exceptions
 All exceptions must be a child of Throwable.
 If we want to write a checked exception that is automatically enforced by the
Handle ,we need to extend the Exception class.
 User defined exception needs to inherit (extends) Exception class in order to act as
an exception.
 throw keyword is used to throw such exceptions.

class MyOwnException extends Exception


{
public MyOwnException(String msg)
{
super(msg);
}
}

class EmployeeTest
{
static void employeeAge(int age) throws MyOwnException
{
if(age < 0)
throw new MyOwnException("Age can't be less than zero");
else
System.out.println("Input is valid!!");
}
public static void main(String[] args)
{
try { employeeAge(-2);
}
catch (MyOwnException e)
{
e.printStackTrace();
}
}
}

Advantages of Exception Handling

 Exception handling allows us to control the normal flow of the program by using
exception handling in program.
 It throws an exception whenever a calling method encounters an error providing that the
calling method takes care of that error.
 It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.

Files and I/O

To process the input and generate an output, Java I/O (Input and Output) is used.

Java utilizes the stream idea to speed up the I/O operation. The java.io package includes
all the classes which are necessary for input and output operations. We can use Java I/O
API to handle files.

The java.io package contains almost every class in Java that you may ever need to
perform input and output (I / O). All these streams are a source of input and a destination
of output. The stream in the java.io package supports a lot of information like primitives,
object, localized characters, etc.

Stream
A stream can be described as a data sequence. There are two types of streams available:

InputStream: The InputStream is used from a source to read data.


OutputStream: To write data to a destination, the OutputStream is used in Java.
Java offers powerful but flexible file and network I/O support, but this tutorial includes
very fundamental stream and I/O functionality. We'll see one by one the most frequently
used instances.

Byte Streams
Java byte streams are used to execute 8-bit bytes input and output. Although there are
many classes linked to byte streams, FileInputStream and FileOutputStream are the
most commonly used classes. Following is an instance to copy an input file into an output
file using these two classes.

Example:

import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("inputFile.txt");
out = new FileOutputStream("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Character Streams

Java Byte streams are used to execute 8-bit bytes input and output while Java Character
streams are used to execute 16-bit Unicode input and output. Although there are many
classes associated with character streams, FileReader and FileWriter are the most
commonly used classes. While FileReader utilizes FileInputStream internally and
FileWriter uses FileOutputStream, the main distinction here is that FileReader reads two
bytes at one moment and FileWriter writes two bytes at one moment.

The above instance can be re-written, which makes use of these two classes to copy an
input file (with Unicode characters) into an output file.

import java.io.*;
public class FileCopyExample {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("inputFile.txt");
out = new FileWriter("outputFile.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Java Standard Streams
All Java programs automatically import the java.lang package. This package defines a class
called System, which encapsulates several aspects of the run-time environment. For example,
using some of its methods, we can obtain the current time and the settings of various properties
associated with the system. System class also contains three predefined stream variables, in,
out, and err. These fields are declared as public and static within System. This means that they
can be used by any other part of our program and without reference to a
specific System object. System.out refers to the standard output stream. By default, this is the
console. System.in refers to standard input, which is the keyboard by default. System.err refers
to the standard error stream, which also is the console by default. However, these streams may be
redirected to any compatible I/O device. System.in is an object of
type InputStream; System.out and System.err are objects of type PrintStream. These are byte
streams, even though they typically are used to read and write characters from and to the console.
We can wrap these within character-based streams, if desired. The preceding chapters have been
using System.out in their examples. We can use System.err in much the same way.
 Standard Input: Accessed through in which is used to read input from the keyboard.
 Standard Output: Accessed through out which is used to write output to the display
(console).
 Standard Error: Accessed through err which is used to write error output to the display
(console).
These objects are defined automatically and do not need to be opened explicitly. Standard
Output and Standard Error, both are to write output; having error output separately so that the
user may read error messages efficiently.
System.in is a byte stream that has no character stream features. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an argument.

InputStreamReader input = new InputStreamReader(System.in);

Tto get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

Below is a basics program, which creates InputStreamReader to read standard input stream until
the user types a "p".

Example:

import java.io. *;

public class MyFirstReadExample {

public static void main(String args[]) throws IOException {

InputStreamReader cin = null;

try {

cin = new InputStreamReader(System.in);

System.out.println("Enter characters, 'p' to quit.");

char c;

do {

c = (char) cin.read();

System.out.print(c);

} while (c!= 'p');

} finally {

if (cin != null) {

cin.close();

}
}

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;

public class FileOutputStreamExample {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

fout.write(65);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

Java FileOutputStream example 2: write string

import java.io.FileOutputStream;

public class FileOutputStreamExample {


public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

String s="Welcome to java.";

byte b[]=s.getBytes();//converting string into byte array

fout.write(b);

fout.close();

System.out.println("success...");

}catch(Exception e){System.out.println(e);}

Output:

Success...

The content of a text file testout.txt is set with the data Welcome to java

testout.txt

Welcome to java.

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
Java FileInputStream class declaration
public class FileInputStream extends InputStream

Java FileInputStream example 2: read all characters


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:

Welcome to java

Java BufferedOutputStream Class


Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer
to store data. It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.For adding the buffer in an OutputStream, use the BufferedOutputStream class.

Syntax for adding the buffer in an OutputStream:

OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\


testout.txt"));
Declaration for Java.io.BufferedOutputStream class:

public class BufferedOutputStream extends FilterOutputStream

import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to java.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Output:
Success
testout.txt
Welcome to java.

Java BufferedInputStream Class


Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.
Example:
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Here, we are assuming that you have following data in "testout.txt" file:

Welcome java

Output:
Welcome java

Java ByteArrayOutputStream Class


Java ByteArrayOutputStream class is used to write common data into
multiple files. In this stream, the data is written into a byte array which can
be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple


streams.

The buffer of ByteArrayOutputStream automatically grows according to data.

Declaration
public class ByteArrayOutputStream extends OutputStream

Example of Java ByteArrayOutputStream


import java.io.*;
public class DataStreamExample {
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");

ByteArrayOutputStream bout=new ByteArrayOutputStream();


bout.write(65);
bout.writeTo(fout1);
bout.writeTo(fout2);

bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Output:

Success...
f1.txt:
A
f2.txt:
A

Java ByteArrayInputStream Class


The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the name
suggests, it can be used to read byte array as input stream.Java ByteArrayInputStream class
contains an internal buffer which is used to read byte array as stream. In this stream, the data is
read from a byte array.The buffer of ByteArrayInputStream automatically grows according to
data.
Declaration:
public class ByteArrayInputStream extends InputStream

Example of Java ByteArrayInputStream

import java.io.*;
public class ReadExample {
public static void main(String[] args) throws IOException {
byte[] buf = { 35, 36, 37, 38 };
// Create the new byte array input stream
ByteArrayInputStream byt = new ByteArrayInputStream(buf);
int k = 0;
while ((k = byt.read()) != -1) {
//Conversion of a byte into character
char ch = (char) k;
System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);
}
}
}
Output:

ASCII value of Character is:35; Special character is: #


ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &

Java DataOutputStream Class


Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.
Declaration:
public class DataOutputStream extends FilterOutputStream implements DataOutput

import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A

Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data from the input stream in
a machine-independent way.Java application generally uses the data output stream to write data
that can later be read by a data input stream.

Java DataInputStream class declaration


public class DataInputStream extends FilterInputStream implements DataInput

import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:

JAVA
Output:

J-A-V-A

Java FileReader Class


Java FileReader class is used to read data from the file. It returns data in byte format like
FileInputStream class.It is character-oriented class which is used for file handling in java.

Java FileReader class declaration

public class FileReader extends InputStreamReader

Example:
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:

Welcome to java.
Output:

Welcome to java.

Java FileWriter Class


Java FileWriter class is used to write character-oriented data to a file. It is character-oriented
class which is used for file handling in java.Unlike FileOutputStream class, you don't need to
convert string into byte array because it provides method to write string directly.

Java FileWriter class declaration


public class FileWriter extends OutputStreamWriter
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to java");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output:
Success...
testout.txt:
Welcome to java.

You might also like