35
UNIT III EXCEPTION HANDLING AND I/O Exceptions - exception hierarchy - throwing and catching exceptions – built-in exceptions, creating own exceptions, Stack Trace Elements. Input / Output Basics – Streams – Byte streams and Character streams – Reading and Writing Console – Reading and Writing Files EXCEPTIONS An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered 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 Handling Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is

ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

UNIT III

EXCEPTION HANDLING AND I/O

Exceptions - exception hierarchy - throwing and catching exceptions – built-in

exceptions, creating own exceptions, Stack Trace Elements. Input / Output Basics –

Streams – Byte streams and Character streams – Reading and Writing Console –

Reading and Writing Files

EXCEPTIONS

An exception is a problem that arises during the execution of a program. An exception

can occur for many different reasons, including the following:

A user has entered 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 Handling

Some of these exceptions are caused by user error, others by programmer error, and

others by physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three

categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user

error or a problem that cannot be foreseen by the programmer. For example, if a file is

to be opened, but the file cannot be found, an exception occurs. These exceptions

cannot simply be ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably

could have been avoided by the programmer. As opposed to checked exceptions,

runtime exceptions are ignored at the time of compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of

the user or the programmer. Errors are typically ignored in your code because you can

rarely do anything about an error. For example, if a stack overflow occurs, an error

will arise. They are also ignored at the time of compilation.

Page 2: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

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.

Errors are not normally trapped form the Java programs. These conditions normally

happen in case of severe failures, which are not handled by the java programs. Errors are

generated to indicate errors generated by the runtime environment. Example : JVM is out of

Memory. Normally programs cannot recover from errors.

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

Class.

Here is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods:

Following is the list of important methods available in the Throwable class.

SN Methods with Description

1

Public StringgetMessage()

Returns a detailed message about the exception that has occurred. This message is

initialized in the Throwable constructor.

2 public Throwable getCause()

Page 3: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

Returns the cause of the exception as represented by a Throwable object.

3public String toString()

Returns the name of the class concatenated with the result of getMessage()

4

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output

stream.

5

public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0

represents the top of the call stack, and the last element in the array represents the

method at the bottom of the call stack.

6

public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any

previous information in the stack trace.

THROWING AND CATCHING EXCEPTIONS

CATCHING EXCEPTIONS

A method catches an exception using a combination of the try and catch keywords. 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, and the syntax for using try/catch looks like

the following:

try

{

//Protected code

}catch(ExceptionName e1)

{

//Catch block

}

A catch statement involves declaring the type of exception you are trying to catch. If

an exception occurs in protected code, the catch block (or blocks) that follows the try is

Page 4: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

checked. If the type of exception that occurred is listed in a catch block, the exception is

passed to the catch block much as an argument is passed into a method parameter.

Multiple catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple catch

blocks looks like the following:

try

{

//Protected code

}catch(ExceptionType1 e1)

{

//Catch block

}catch(ExceptionType2 e2)

{

//Catch block

}catch(ExceptionType3 e3)

{

//Catch block}

The previous statements demonstrate three catch blocks, but you can have any

number of them after a single try. If an exception occurs in the protected code, the exception

is thrown to the first catch block in the list.

If the data type of the exception thrown matches ExceptionType1, it gets caught

there. If not, the exception passes down to the second catch statement. This continues until

the exception either is caught or falls through all catches, in which case the current method

stops execution and the exception is thrown down to the previous method on the call stack.

THROWING EXCEPTIONS

The throws/throw Keywords:

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.

Page 5: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

A method can declare that it throws more than one exception, in which case the

exceptions are declared in a list separated by commas. For example, the following method

declares that it throws a RemoteException and an InsufficientFundsException:

import java.io.*;

public class className

{

public void withdraw(double amount) throws RemoteException,

InsufficientFundsException

{

// Method implementation

}

//Remainder of class definition

}

The finally Keyword

The finally keyword is used to create a block of code that follows a try block. A finally block

of code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute,

no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try

{

//Protected code

}catch(ExceptionType1 e1)

{

//Catch block

}catch(ExceptionType2 e2)

{

//Catch block

}catch(ExceptionType3 e3)

{

Page 6: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

//Catch block

}finally

{

//The finally block always executes.

}

Example:

public class ExcepTest{

public static void main(String args[]){

int a[] = new int[2];

try{

System.out.println("Access element three :" + a[3]);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Exception thrown :" + e);

}

finally{

a[0] = 6;

System.out.println("First element value: " +a[0]);

System.out.println("The finally statement is executed");

} }}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3

First element value: 6

The finally statement is executed

Note the following:

A catch clause cannot exist without a try statement.

It is not compulsory to have finally clauses when ever a try/catch block is present.

The try block cannot be present without either catch clause or finally clause.

Any code cannot be present in between the try, catch, finally blocks.

Page 7: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

Common Exceptions:

In Java, it is possible to define two catergories of Exceptions and Errors.

JVM Exceptions: - These are exceptions/errors that are exclusively or logically

thrown by the JVM. Examples : NullPointerException,

ArrayIndexOutOfBoundsException, ClassCastException,

Programmatic exceptions: - These exceptions are thrown explicitly by the

application or the API programmers Examples: IllegalArgumentException,

IllegalStateException.

BUILT-IN EXCEPTIONS

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions

are suitable to explain certain error situations. Below is the list of important built-in

exceptions in Java.

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) {

Page 8: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

            System.out.println("Can't divide a number by 0");        }    }}

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");

        }

    }

}

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());

    }

Page 9: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

}

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");

        }

    }

}

Page 10: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

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

interruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it

is interrupted.

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

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

represents nothing

NumberFormatException : This exception is raised when a method could not convert a string into a

numeric format.

StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is

either negative than the size of the string.

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;

    }

}

StackOverflowError

// Java Program to illustrate

// StackOverflowError

class Test {

public static void main(String[] args)

    {

Page 11: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

        m1();

    }

public static void m1()

    {

        m2();

    }

public static void m2()

    {

        m1();

    }}

NoClassDefFoundError

// Java Program to illustrate

// NoClassDefFoundError

class Test //

    {

public static void main(String[] args)

    {

        System.out.println("HELLO GEEKS");

    }}

ExceptionInInitializerError

Code 1:

// Java Program to illustrate

// ExceptionInInitializerError

class Test {

    static int x = 10 / 0;

public static void main(String[] args)

    {    }}

IllegalArgumentException

// Java Program to illustrate

// IllegalArgumentException

class Test {

public static void main(String[] args)

    {

Page 12: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

        Thread t = new Thread();

        Thread t1 = new Thread();

        t.setPriority(7); // Correct

        t1.setPriority(17); // Exception

    }}

IllegalArgumentException

// Java Program to illustrate

// IllegalStateException

class Test {

public static void main(String[] args)

    {

        Thread t = new Thread();

        t.start();

        t.start();

    }}

AssertionError

// Java Program to illustrate

// AssertionError

class Test {

public static void main(String[] args)    {

        // If x is not greater than or equal to 10

        // then we will get the run-time exception

        assert(x >= 10);    }}

CREATING OWN EXCEPTIONS

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing

your own exception classes:

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle

or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the Runtime Exception

class.We can define our own Exception class as below:

Page 13: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

class MyException extends Exception{

}

STACK TRACE ELEMENTS

A stack trace is a list of the method calls that the application was in the middle of

when an Exception was thrown. An element in a stack trace, as returned

by Throwable.getStackTrace(). Each element represents a single stack frame. All stack

frames except for the one at the top of the stack represent a method invocation. The frame at

the top of the stack represents the execution point at which the stack trace was generated.

Typically, this is the point at which the throwable corresponding to the stack trace was

created.

public final class StackTraceElement

extends Object

implements Serializable

INPUT / OUTPUT BASICS

Java IO is an API that comes with Java which is targeted at reading and writing data

(input and output). Most applications need to process some input and produce some output

based on that input. For instance, read data from a file or over network, and write to a file or

write a response back over the network

Programming simple I/O operations is easy, which involves only a few classes and

methods. You could do it by looking at a few samples. Programming efficient, portable I/O

is extremely difficult, especially if you have to deal with different character sets.

JDK has two sets of I/O packages:

1. the Standard I/O (in package java.io), introduced since JDK 1.0 for stream-based I/O,

and

2. the New I/O (in packages java.nio), introduced in JDK 1.4, for more efficient buffer-

based I/O.

Page 14: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

STREAMS

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a

stream because it's like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are attached with

console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and error message to the console.

1. System.out.println("simple message");  

2. System.err.println("error message");  

Let's see the code to 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.

Let's understand working of Java OutputStream and InputStream by the figure given below.

Page 15: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

OutputStream class

OutputStream class is an abstract class.It is the superclass of all classes representing

an output stream of bytes. An output stream accepts output bytes and sends them to some

sink.

Commonly used methods of OutputStream class

Method Description

1) public void write(int)throws

IOException:

is used to write a byte to the current output

stream.

2) public void write(byte[])throws

IOException:

is used to write an array of byte to the current

output stream.

3) public void flush()throws

IOException:flushes the current output stream.

4) public void close()throws

IOException:is used to close the current output stream.

Page 16: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

InputStream class

InputStream class is an abstract class.It is the superclass of all classes representing an

input stream of bytes.

Commonly used methods of InputStream class

Method Description

1) public abstract int read()throws

IOException:

reads the next byte of data from the input stream.It

returns -1 at the end of file.

2) public int available()throws

IOException:

returns an estimate of the number of bytes that can be

read from the current input stream.

3) public void close()throws

IOException:is used to close the current input stream.

BYTE STREAMS AND CHARACTER STREAMS

Byte Stream

Byte streams process data byte by byte (8 bits). For example FileInputStream is used

to read from source and FileOutputStream to write to the destination.

// Java Program illustrating the Byte Stream to copy

Page 17: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

// contents of one file to another file.

import java.io.*;  

public class BStream{

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

        FileInputStream sourceStream = null;

        FileOutputStream targetStream = null;

         try        {

            sourceStream = new FileInputStream("sorcefile.txt");

            targetStream = new FileOutputStream ("targetfile.txt");

 

            // Reading source file and writing content to target

            // file byte by byte

            int temp;

            while ((temp = sourceStream.read()) != -1)

                targetStream.write((byte)temp);      

        }

        finally        {

            if (sourceStream != null)

                sourceStream.close();           

            if (targetStream != null)           

                targetStream.close();         }    }}

Character Stream

In Java, characters are stored using Unicode conventions (Refer this for details).

Character stream automatically allows us to read/write data character by character. For

example FileReader and FileWriter are character streams used to read from source and write

Page 18: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

to destination.

import java.io.*;   // Accessing FileReader, FileWriter, IOException

public class GfG{

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

        FileReader sourceStream = null;

        try        {

            sourceStream = new FileReader("test.txt");

                                      int temp;

            while ((temp = sourceStream.read()) != -1)

                 System.out.println((char)temp);        }

        finally        {           

            // Closing stream as no longer in use

            if (sourceStream != null)           

                sourceStream.close();             }    }}

When to use Byte Stream over  Character Stream? 

Byte oriented reads byte by byte.  A byte stream is suitable for processing raw data like binary files.

Page 19: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

READING AND WRITING CONSOLE

In Java, there are three different ways for reading input from the user in the command

line environment (console).

Using Buffered Reader Class

This is the Java classical method to take input, Introduced in JDK1.0. This method is

used by wrapping the System.in (standard input stream) in an InputStreamReader which is

wrapped in a BufferedReader, we can read input from the user in the command line.

Advantages

The input is buffered for efficient reading.

Drawback:

The wrapping code is hard to remember.

Program:

// Java program to demonstrate BufferedReader

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class Test

{

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

    {

        //Enter data using BufferReader

        BufferedReader reader =

                   new BufferedReader(new InputStreamReader(System.in));

        

        // Reading data using readLine

        String name = reader.readLine();

 

        // Printing the read line

        System.out.println(name);       

    }

}

Page 20: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner

class is to parse primitive types and strings using regular expressions, however it is also can

be used to read input from the user in the command line.

Advantages:

Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the

tokenized input.

Regular expressions can be used to find tokens.

Drawback:

The reading methods are not synchronized

// Java program to demonstrate working of Scanner in Java

import java.util.Scanner;

 class GetInputFromUser{

    public static void main(String args[])    {

        // Using Scanner for Getting Input from User

        Scanner in = new Scanner(System.in);

         String s = in.nextLine();

        System.out.println("You entered string "+s);

         int a = in.nextInt();

        System.out.println("You entered integer "+a);

         float b = in.nextFloat();

        System.out.println("You entered float "+b);    }}

Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In

addition, it can be used for reading password-like input without echoing the characters

Page 21: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

entered by the user; the format string syntax can also be used (like System.out.printf()).

Advantages:

Reading password without echoing the entered characters.

Reading methods are synchronized.

Format string syntax can be used.

Drawback:

Does not work in non-interactive environment (such as in an IDE).

// Java program to demonstrate working of System.console()

// Note that this program does not work on IDEs as

// System.console() may require console

public class Sample {

    public static void main(String[] args)     {       

        // Using Console to input data from user

        String name = System.console().readLine();         

        System.out.println(name);    }}

READING AND WRITING FILES

FileReader (for text files) should usually be wrapped in a BufferedFileReader. This

saves up data so you can deal with it a line at a time or whatever instead of character by

character. If you want to write files, basically all the same stuff applies, except you'll deal

with classes named FileWriterwith BufferedFileWriter for text files,

or FileOutputStream for binary files. 

We can read files using these classes: 

FileReader for text files in your system's default encoding

FileInputStream for binary files and text files that contain 'weird' characters. 

Reading Ordinary Text Files in Java

If you want to read an ordinary text file in your system's default encoding (usually the

case most of the time for most people), use FileReader and wrap it in a BufferedReader. 

In the following program, we read a file called "temp.txt" and output the file line by line on

the console. 

import java.io.*;

public cass Test {

Page 22: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

public static void main(String [] args) {

// The name of the file to open.

String fileName = "temp.txt";

// This will reference one line at a time

String ine = null;

try {

// FileReader reads text files in the default encoding.

FileReader fileReader =

new FileReader(fileName);

// Always wrap FileReader in BufferedReader.

BufferedReader bufferedReader =

new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {

System.out.println(line);

}

// Always close files.

bufferedReader.close();

}

catch(FileNotFoundException ex) {

System.out.println(

"Unable to open file '" +

fileName + "'");

} catch(IOException ex) {

System.out.println(

Page 23: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

"Error reading file '"

+ fileName + "'");

// Or we could just do this:

// ex.printStackTrace();

} }}

Reading Binary Files in Java

If you want to read a binary file, or a text file containing 'weird' characters (ones that

your system doesn't deal with by default), you need to use FileInputStream instead of

FileReader. Instead of wrapping FileInputStream in a buffer, FileInputStream defines a

method called read() that lets you fill a buffer with data, automatically reading just enough

bytes to fill the buffer (or less if there aren't that many bytes left to read). 

Here's a complete example. 

import java.io.*;

public class Test {

public static void main(String [] args) {

// The name of the file to open.

String fileName = "temp.txt";

try {

// Use this for reading the data.

byte[] buffer = new byte[1000];

FileInputStream inputStream =

new FileInputStream(fileName);

// read fills buffer with data and returns

// the number of bytes read (which of course

// may be less than the buffer size, but

Page 24: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

// it will never be more).

int total = 0;

int nRead = 0;

while((nRead = inputStream.read(buffer)) != -1) {

// Convert to String so we can display it.

// Of course you wouldn't want to do this with

// a 'real' binary file.

System.out.println(new String(buffer));

total += nRead;

}

// Always close files.

inputStream.close();

System.out.println("Read " + total + " bytes");

}

catch(FileNotFoundException ex) {

System.out.println(

"Unable to open file '" +

fileName + "'");

} catch(IOException ex) {

System.out.println(

"Error reading file '"

+ fileName + "'");

// Or we could just do this:

// ex.printStackTrace(); } }}

Page 25: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

Writing Text Files in Java

To write a text file in Java, use FileWriter instead of FileReader,

and BufferedOutputWriter instead of BufferedOutputReader.

Here's an example program that creates a file called 'temp.txt' and writes some lines of text to

it. 

import java.io.*;

public class Test {

public static void main(String [] args) {

// The name of the file to open.

String fileName = "temp.txt";

try {

// Assume default encoding.

FileWriter fileWriter =

new FileWriter(fileName);

// Always wrap FileWriter in BufferedWriter.

BufferedWriter bufferedWriter =

new BufferedWriter(fileWriter);

// Note that write() does not automatically

// append a newline character.

bufferedWriter.write("Hello there,");

bufferedWriter.write(" here is some text.");

bufferedWriter.newLine();

bufferedWriter.write("We are writing");

bufferedWriter.write(" the text to the file.");

// Always close files.

Page 26: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

bufferedWriter.close();

}

catch(IOException ex) {

System.out.println(

"Error writing to file '"

+ fileName + "'");

// Or we could just do this:

// ex.printStackTrace();

} }}

Writing Binary Files in Java

You can create and write to a binary file in Java using much the same techniques that

we used to read binary files, except that we need FileOutputStream instead

of FileInputStream. 

In the following example we write out some text as binary data to the file. Usually of course,

you'd probably want to write some proprietary file format or something. 

import java.io.*;

public class Test {

public static void main(String [] args) {

// The name of the file to create.

String fileName = "temp.txt";

try {

// Put some bytes in a buffer so we can

// write them. Usually this would be

// image data or something. Or it might

Page 27: ajitha2017.files.wordpress.com  · Web viewIf the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second

// be unicode text.

String bytes = "Hello theren";

byte[] buffer = bytes.getBytes();

FileOutputStream outputStream =

new FileOutputStream(fileName);

// write() writes as many bytes from the buffer

// as the length of the buffer. You can also

// use

// write(buffer, offset, length)

// if you want to write a specific number of

// bytes, or only part of the buffer.

outputStream.write(buffer);

// Always close files.

outputStream.close();

System.out.println("Wrote " + buffer.length +

" bytes"); }

catch(IOException ex) {

System.out.println(

"Error writing file '"

+ fileName + "'");

// Or we could just do this:

// ex.printStackTrace(); } }}