io package as java’s basic i/o system cont’d

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

Upload: vevay

Post on 26-Jan-2016

45 views

Category:

Documents


1 download

DESCRIPTION

io package as Java’s basic I/O system cont’d. Reading and Writing Files. Java provides a number of classes and methods that allow us to read and write files In Java, all files are byte-oriented Java provides methods to read and write bytes from and to a file - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: io package as Java’s basic I/O system cont’d

io package as Java’s basic I/O system

cont’d

Reading and Writing Files

Page 2: io package as Java’s basic I/O system cont’d

Java provides a number of classes and methods that allow us to read and write files

In Java, all files are byte-oriented

Java provides methods to read and write bytes from and to a file

Java allows us to wrap a byte-oriented file-stream within a character based object

The two of most often-used stream classes are FileInputStream and FileOutputStream,

which create byte streams linked to files

Page 3: io package as Java’s basic I/O system cont’d

To open a file, we simply create an object of one of the stream classes

by specifying the name of the file as an argument to the constructor

While FileInputStream and FileOutputStream classes support additional overriden constructors, we can write the followings:

FileInputStream(String fileName) throws FileNotFoundException

FileOutStream (String fileName) throws FileNotFoundExceptionfileName specifies the name of the file that we want to

openWhen we create an input stream, if the file does not

exist, then FileNotFoundException is thrownWhen an output file is opened, any preexisting file by

the same name is destroyed. When we use a file, you should close it calling close(). It is defined by both FileInputStream and FileOutputStream

as follows: void close() throws IOException

Page 4: io package as Java’s basic I/O system cont’d

Character Streams versus Byte Streams

The java.io package provides classes that allow us to convert between Unicode character streams and byte streams of non-Unicode text.

With the InputStreamReader class, we can convert byte streams to character streams.

With the OutputStreamWriter class, we can translate character streams into byte streams.

Page 5: io package as Java’s basic I/O system cont’d

Most of the functionality available for byte streams is also provided for character streams.

The methods for character streams generally accept parameters of data type char parameters, while byte streams work with byte data types.

The names of the methods in both sets of classes are almost identical except for the suffix,

Character-stream classes end with the suffix Reader or Writer and byte-stream classes end with the suffix InputStream and OutputStream.

For example, to read files using character streams, you would use the java.io.FileReader class; for reading it using byte streams you would use java.io.FileInputStream.

Page 6: io package as Java’s basic I/O system cont’d

When we create InputStreamReader and OutputStreamWriter objects,

We specify the byte encoding that we want to convert.

For example, to translate a text file in the UTF-8 encoding into Unicode, we create an InputStreamReader as follows:

FileInputStream fis = new FileInputStream ("test.txt");

InputStreamReader isr = new InputStreamReader (fis, "UTF8");

Page 7: io package as Java’s basic I/O system cont’d

Writing Files To write a file, we use the write() method

defined by FileOutSteam Its the simplest form is shown here:

void write (int byteval ) throwsIOException This method writes the byte specified by

byteval to the file. Although byteval is declared as an integer,

only low order eight bits are written to the file.

Page 8: io package as Java’s basic I/O system cont’d

What is Unicode? Unicode provides a unique number for every character,

no matter what the platform, no matter what the program, no matter what the language.

Computers just deal with numbers. They store letters and other characters by assigning a number

for each one.

Before Unicode was invented, there were hundreds of different encoding

No single encoding could contain enough characters: The European Union alone requires several different

encodings to cover all its languages. Even for a single language like English no single encoding

was adequate for all the letters, punctuation, and technical symbols in common use.

Page 9: io package as Java’s basic I/O system cont’d

What is Unicode?con’t

These encoding systems also conflict with one another.

Two encodings can use the same number for two different characters, or use different numbers for the same character.

Any given computer (especially servers) needs to support many different encodings

Whenever data is passed between different encodings or platforms, that data always runs the risk of corruption.

Unicode is well on the way to replace ASCII, ISO 8859 and EUC at all levels

Page 10: io package as Java’s basic I/O system cont’d

What is UTF-8?

UTF-8 stands for Unicode Transformation Format-8. It is an

octet (8-bit) lossless encoding of Unicode characters.

With the UTF-8 encoding, Unicode can be used in a convenient and backwards compatible way in environments that, like Unix, were designed entirely around ASCII.

UTF-8 is the way in which Unicode is used under Unix, Linux, and similar systems. It is now time to make sure that you are well familiar with it and that your software supports UTF-8 smoothly.

Page 11: io package as Java’s basic I/O system cont’d

To read from a file, we can use read() that is defined within FileInputStream.

int read() throws IOException Each time that it is called, it reads a single byte from the file,

and returns byte as an integer value.

int read() returns an integer representation of the next available byte of input. -1 when the end of the file is encountered.

It can throw an IOException

Page 12: io package as Java’s basic I/O system cont’d

Various Stream Classes The java.io package contains the Java I/O stream classes. These classes are either the top level abstract classes or the

specialized descendant implementation classes, both types are described below.

Top Level Classes: java.io.Reader and java.io.Writer

Reader and Writer are the abstract parent classes for character-stream based classes in the java.io package.

The methods for reading and writing to streams found in these and their descendent classes are:

int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length)

Page 13: io package as Java’s basic I/O system cont’d

/*This program uses read() to input and display the contents of a text file */

import java.io.*;class ShowFile { public static void main (String args[ ]) throws IOException{ int i; FileInputStream fin; try { fin= new FileInputStream(args[0]);} catch (FileNotFoundException e) { System.out.println ("File Not Found"); return;} catch (ArrayIndexOutOfBoundsException e ) { System.out.println ("Usage:Show File File"); return;}//read characters until EOF is encountered do { i=fin.read(); if (i!=-1) System.out.print ((char) i); } while( i!= -1); fin.close(); }

Page 14: io package as Java’s basic I/O system cont’d

Exception Handling Fundamentals

A Java exception is an object that describes an exception (that is error) condition that has occurred in a piece of code.

When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused an error.

Java exception handling is managed via five keywords: try, catch, throw, throws, finally

Page 15: io package as Java’s basic I/O system cont’d

General form of an exception-handling block

try {// block code to monitor for errors}catch (Exception Type1 exOB) { //exception handler for ExceptionType1}catch (ExceptionType2 exOB) {//exception handler for exceptionType2}//..finally {//block code to be executed before try block ends}

Page 16: io package as Java’s basic I/O system cont’d

Execution Types All exception types are subclass of the built-in-class Throwable Throwable is at the top of the exception class hierarchy Throwable has two subclasses that are partition exceptions:

ExceptionThis class is used for exceptional conditions that

user programs should catchAn important subclass of exception called

RuntimeExceptionError

Defines exceptions that are not caught under normal circumstances

Exception types of error are used by the java run-time system to indicate errors having to do with the run-time environment

Page 17: io package as Java’s basic I/O system cont’d

RuntimeException

public RuntimeException() Constructs a RuntimeException with no detail message.

public RuntimeException ( String  s) Constructs a RuntimeException with the specified

detail message. Parameters: s - the detail message.

java.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException

Page 18: io package as Java’s basic I/O system cont’d

Uncaught Exceptions

/*This program includes an expression that intentionally causes a divide by zero error*/

class A { public static void main (String args[]) {int d= 0;int a= 15/d; } } When Java runtime system detects the attempt to

divide by zero, it constructs a new exception object and then throws this exception

This causes A to stop

Page 19: io package as Java’s basic I/O system cont’d

java.lang.ArithmeticException: /by zero at A.main(A.java:6)

The class name A, the method name main, the filename A.java , and the line number 6 in the simple stack tree

The type of exception thrown is a subclass of Exception called ArithmeticException

Page 20: io package as Java’s basic I/O system cont’d

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

This program generates the following output:After catch statement

Page 21: io package as Java’s basic I/O system cont’d

The call to print() inside try block is never executed. Once an exception is thrown, program control

transfers out of the try block into the catch block

Put differently,

catch is not “called”, so execution never “returns” to try block from a catch

Thus The line “This will not be printed” is not displayed

Once the catch statement is executed, program control continues with the next line in the program following the entire try/catch mechanism.

Page 22: io package as Java’s basic I/O system cont’d

A try and its catch statement form a unit The scope of the catch clause is restricted to

those statements specified by the immediately proceeding try statement

A catch statement cannot catch an exception thrown by another try statement

The statements that are protected by try must be surrounded by curly braces.

We cannot use try on a single statement The goal of most catch clauses should be to

resolve the exceptional condition and then continue as if the error had never stopped.

Page 23: io package as Java’s basic I/O system cont’d

Homework Using Random() constructor (that creates a new

random number generator) to obtain two random integers. (a and b)

Then divide two integers by each other (a/b) The result value is used to divide the 12345. (12345/ (a/b))Use try catch statements for the possibility of divide-

by-zero error.Hint: use nextInt method to return the next

pseudorandom, uniformly distributed int value from the random number generator's sequence.

Here you have to use inheritance propery of random() class.

Page 24: io package as Java’s basic I/O system cont’d

Class FileNotFoundExceptionjava.lang.Object java.lang.Throwable java.lang.Exception java.io.IOexception java.io.FileNotFoundException This exception will be thrown by the

FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.

It will also be thrown by these constructors if the file does exist but for some reason is inaccessible,

For example: when an attempt is made to open a read-only file for writing.

Page 25: io package as Java’s basic I/O system cont’d

Class ArrayIndexOutOfBoundsExceptionjava.lang.Object java.lang.Throwable java.lang.Exception java.lang.RuntimeException

java.lang.IndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException

The object is thrown to indicate that an array has been accessed

with an illegal index. The index is either negative orgreater than or equal to the size of the array.

The constructor ArrayIndexOutOfBoundsException()  constructs an ArrayIndexOutOfBoundsException with no detail message.

Page 26: io package as Java’s basic I/O system cont’d

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

return; }//open output file try { fout= new FileOutPutStream (args[1]); }

Page 27: io package as Java’s basic I/O system cont’d

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