i/o basics 12 january 2014smitha n. pai, cse dept.1

125
I/O Basics July 2, 2022 Smitha N. Pai, CSE Dept. 1

Upload: ava-garcia

Post on 26-Mar-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

I/O Basics

April 10, 2023 Smitha N. Pai, CSE Dept. 1

Page 2: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

In fact, aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real applications of Java are not text-based, console programs.

they are graphically oriented applets that rely upon Java’s Abstract Window Toolkit (AWT) for interaction with the user.

Java’s support for console I/O is limited and somewhat awkward to use—even in simple example programs. Text-based console I/O is just not very important to Java programming.

April 10, 2023 Smitha N. Pai, CSE Dept. 2

Page 3: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Streams Java programs perform I/O through streams. A stream is an abstraction that either produces

or consumes information. A stream is linked to a physical device by the

Java I/O system. All streams behave in the same manner, even if

the actual physical devices to which they are linked differ.

Same I/O classes and methods can be applied to any type of device..

April 10, 2023 Smitha N. Pai, CSE Dept. 3

Page 4: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Streams(contd.) Input stream can abstract many different kinds of

input: from a disk file, a keyboard, or a network socket.

Output stream may refer to the console, a disk file, or a network connection.

Streams deal with input/output without having every part of your code understand the difference between a keyboard and a network.

Java implements streams within class hierarchies defined in the java.io package.

April 10, 2023 Smitha N. Pai, CSE Dept. 4

Page 5: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Byte Streams and Character Streams Java 2 defines two types of streams: byte and character.

Byte streams provide means for handling input and output of bytes and are used for reading or writing binary data.

Character streams handles input and output of characters. They use Unicode and, therefore, can be internationalized.

Character streams are more efficient than byte streams.

At the lowest level, all I/O is byte-orientedApril 10, 2023 Smitha N. Pai, CSE Dept. 5

Page 6: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Byte Stream Classes Byte streams are defined by using two class

hierarchies. At the top are two abstract classes: InputStream and OutputStream.

Each of these abstract classes has several concrete subclasses, that handle the differences between various devices, such as disk files, network connections, and even memory buffers.

to use the stream classes, you must import java.io. The abstract classes InputStream and

OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ),

April 10, 2023 Smitha N. Pai, CSE Dept. 6

Page 7: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream.

They are overridden by derived stream classes.

The Character Stream Classes Character streams are defined by using two

class hierarchies. At the top are two abstract classes, Reader and

Writer , which define several key methods that the other stream classes implement.

April 10, 2023 Smitha N. Pai, CSE Dept. 7

Page 8: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

These abstract classes handle Unicode character streams.

Java has several concrete subclasses of each of these.

Two of the most important methods are read( ) and write( ),which read and write characters of data, respectively.

These methods are overridden by derived stream classes

First slide is Byte Stream classes Second slide is the character stream I/O classes

April 10, 2023 Smitha N. Pai, CSE Dept. 8

Page 9: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 9

Page 10: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 10

Page 11: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Predefined Streams java.lang package defines a class called System,

which encapsulates several aspects of the run-time environment.

Using some of its methods, you can do the settings of various properties associated with the system.

System also contains three predefined stream variables, in, out, and err.

These fields are declared as public and static within System.

They can be used by any other part of the program and without reference to a specific System object.

April 10, 2023 Smitha N. Pai, CSE Dept. 11

Page 12: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

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.

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, used to read and write

characters from and to the console.April 10, 2023 Smitha N. Pai, CSE Dept. 12

Page 13: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Reading Console Input Console input is accomplished by reading from

System.in. To obtain character-based stream that is

attached to the console, you wrap System.in in a BufferedReader object, to create a character stream.

BuffereredReader supports a buffered input stream.

Constructor is shown here: BufferedReader(Reader inputReader)

April 10, 2023 Smitha N. Pai, CSE Dept. 13

Page 14: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

inputReader is the stream that is linked to the instance of BufferedReader that is being created.

Reader is an abstract class. One of its concrete subclasses is

InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

April 10, 2023 Smitha N. Pai, CSE Dept. 14

Page 15: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

System.in refers to an object of type InputStream, it can be used for inputStream.

The following line of code creates a BufferedReader that is connected to the keyboard:

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

Reading Characters To read a character from a BufferedReader,

use read( ). int read( ) throws IOExceptionApril 10, 2023 Smitha N. Pai, CSE Dept. 15

Page 16: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

It reads a character from the input stream and returns it as an integer value.

It returns –1 when the end of the stream is encountered. It can throw an IOException.

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead {

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

{ char c;

BufferedReader br = new

BufferedReader(new InputStreamReader(System.in));April 10, 2023 Smitha N. Pai, CSE Dept. 16

Page 17: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

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

// read characters

do { c = (char) br.read();

System.out.println(c);

} while(c != 'q'); } }

Enter characters, 'q' to quit. 123abcq

1

2

3

a

b

c

q System.in line buffered, by default. This means that no input is actually passed to the program until you press ENTER.April 10, 2023 Smitha N. Pai, CSE Dept. 17

Page 18: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Reading Strings To read a string from the keyboard, use the version of

readLine( ) that is a member of the BufferedReader class.

Its general form is shown here:

String readLine( ) throws IOException It returns a String object.

import java.io.*;

class BRReadLines {

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

{ // create a BufferedReader using System.in

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

April 10, 2023 Smitha N. Pai, CSE Dept. 18

Page 19: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

String str;

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

do {

str = br.readLine();

System.out.println(str);

} while(!str.equals("stop"));

} }

import java.io.*; //A tiny Editor

class TinyEdit {

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

// create a BufferedReader using System.in

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

April 10, 2023 Smitha N. Pai, CSE Dept. 19

Page 20: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

String str[] = new String[100];

System.out.println("Enter lines of text.");

System.out.println("Enter 'stop' to quit.");

for(int i=0; i<100; i++) {

str[i] = br.readLine();

if(str[i].equals("stop")) break; }

System.out.println("\nHere is your file:");

// display the lines

for(int i=0; i<100; i++) {

if(str[i].equals("stop")) break;

System.out.println(str[i]); }

}

}

.April 10, 2023 Smitha N. Pai, CSE Dept. 20

Page 21: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Here is a sample run:

Enter lines of text.

Enter 'stop' to quit.

This is line one.

This is line two.

Just create String objects.

stop

Here is your file:

This is line one.

This is line two.

Just create String objects

April 10, 2023 Smitha N. Pai, CSE Dept. 21

Page 22: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Writing Console Output

PrintStream is an output stream derived from OutputStream, it implements the low-level method write( ).

write( ) can be used to write to the console:

void write(int byteval) This method writes to the stream the byte

specified by byteval. byteval is declared as an integer, only the low-

order eight bits are written.

April 10, 2023 Smitha N. Pai, CSE Dept. 22

Page 23: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

class WriteDemo {

public static void main(String args[]) {

int b;

b = 'A';

System.out.write(b);

System.out.write('\n');

}

}

Writes A to the console and adds a new line.

April 10, 2023 Smitha N. Pai, CSE Dept. 23

Page 24: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

File The File class does not operate on stream It deals directly with files and the file system. File class does not specify how information is

retrieved from or stored in files; it describes the properties of a file itself.

A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies.

April 10, 2023 Smitha N. Pai, CSE Dept. 24

Page 25: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

A directory in Java is treated as a File with one additional property—a list of filenames that can be examined by the list( ) method.

The following constructors can be used to create File objects: File(String directoryPath) File(String directoryPath, String filename) File(File dirObj, String filename) File(URI uriObj)

Here, directoryPath is the path name of the file, filename is the name of the file, dirObj is a File object that specifies a directory, and uriObj is a URI object that describes a file.

April 10, 2023 Smitha N. Pai, CSE Dept. 25

Page 26: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The following example creates three files: f1, f2, and f3. The first File object is constructed with a directory path as the only argument. The second includes two arguments—the path and the filename. The third includes the file path assigned to f1 and a filename; f3 refers to the same file as f2.

File f1 = new File("/"); File f2 = new File("/","autoexec.bat"); File f3 = new File(f1,"autoexec.bat");

import java.io.File; // Demonstrate File

class FileDemo {

static void p(String s) {

System.out.println(s); }

public static void main(String args[]) {

File f1 = new File("/java/COPYRIGHT");

p("File Name: " + f1.getName());April 10, 2023 Smitha N. Pai, CSE Dept. 26

Page 27: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

p("Path: " + f1.getPath());

p("Abs Path: " + f1.getAbsolutePath());

p("Parent: " + f1.getParent());

p(f1.exists() ? "exists" : "does not exist");

p(f1.canWrite() ? "is writeable" : "is not writeable");

p(f1.canRead() ? "is readable" : "is not readable");

p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));

p(f1.isFile() ? "is normal file" : "might be a named pipe");

p(f1.isAbsolute() ? "is absolute" : "is not absolute");

p("File last modified: " + f1.lastModified());

p("File size: " + f1.length() + " Bytes");

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 27

Page 28: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

File Name: COPYRIGHT

Path: /java/COPYRIGHT

Abs Path: /java/COPYRIGHT

Parent: /java

exists

is writeable

is readable

is not a directory

is normal file

is absolute

File last modified: 812465204000

File size: 695 BytesApril 10, 2023 Smitha N. Pai, CSE Dept. 28

Page 29: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

isFile( ) returns false for some special files, such as device drivers and named pipes, so this method can be used to make sure the file will behave as a file.

The isAbsolute( ) method returns true if the file has an absolute path and false if its path is relative.

April 10, 2023 Smitha N. Pai, CSE Dept. 29

Page 30: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 30

Directories•A directory is a File that contains a list of other files and directories.•The isDirectory( ) method will return true when you create a File object and its directory. list( ) is called on the object to extract the list of other files and directories present inside.

Page 31: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Two forms are: String[ ] list( ) String[ ] list(FilenameFilter FFObj)

The list of files is returned in an array of String objects.// Using directories.

import java.io.File;

class DirList {

public static void main(String args[]) {

String dirname = "/java";

File f1 = new File(dirname);

if (f1.isDirectory()) {

System.out.println("Directory of " + dirname);

April 10, 2023 Smitha N. Pai, CSE Dept. 31

Page 32: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

String s[] = f1.list();

for (int i=0; i < s.length; i++) {

File f = new File(dirname + "/" + s[i]);

if (f.isDirectory()) {

System.out.println(s[i] + " is a directory");

} else {

System.out.println(s[i] + " is a file"); } }

} else {

System.out.println(dirname + " is not a directory");

}

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 32

Page 33: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Here is sample output from the program.

Directory of /java

bin is a directory

lib is a directory

demo is a directory

COPYRIGHT is a file

README is a file

index.html is a file

include is a directory

src.zip is a file

hotjava is a directory

src is a directory

April 10, 2023 Smitha N. Pai, CSE Dept. 33

Page 34: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Using FilenameFilter The list( ) method includes only those files that

match a certain filename pattern, or filter. String[ ] list(FilenameFilter FFObj)

FFObj is an object of a class that implements the FilenameFilter interface.

FilenameFilter defines only a single method, accept( ), which is called once for each file in a list. boolean accept(File directory, String filename)

April 10, 2023 Smitha N. Pai, CSE Dept. 34

Page 35: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The accept( ) method returns true for files in the directory specified by directory that should be included in the list (that is, those that match the filename argument), and returns false for those files that should be excluded.

import java.io.*; //restricts the visibility of file names returned

public class OnlyExt implements FilenameFilter {

String ext;

public OnlyExt(String ext) {

this.ext = "." + ext;

}

public boolean accept(File dir, String name) {

return name.endsWith(ext); }

}

April 10, 2023 Smitha N. Pai, CSE Dept. 35

Page 36: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Directory of .HTML files.

import java.io.*; //only display files with .html

class DirListOnly {

public static void main(String args[]) {

String dirname = "/java";

File f1 = new File(dirname);

FilenameFilter only = new OnlyExt("html");

String s[] = f1.list(only);

for (int i=0; i < s.length; i++) {

System.out.println(s[i]);

} } }

April 10, 2023 Smitha N. Pai, CSE Dept. 36

Page 37: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The listFiles( ) Alternative File[ ] listFiles( ) File[ ] listFiles(FilenameFilter FFObj) File[ ] listFiles(FileFilter FObj)

These methods return the file list as an array of File objects instead of strings.

The first method returns all files, and the second returns those files that satisfy the specified FilenameFilter.

The third version of listFiles( ) returns those files with path names that satisfy the specified FileFilter

April 10, 2023 Smitha N. Pai, CSE Dept. 37

Page 38: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The listFiles( ) Alternative FileFilter defines only a single method,

accept( ) which is called once for each file in a list. boolean accept(File path)

The accept( ) method returns true for files that should be included in the list (that is, those that match the path argument), and false for those that should be excluded.

April 10, 2023 Smitha N. Pai, CSE Dept. 38

Page 39: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Creating Directories File utility methods - mkdir( ) and mkdirs( ). The mkdir( ) method creates a directory,

returning true on success and false on failure. Failure indicates that the path specified in the

File object already exists, or that the directory cannot be created because the entire path does not exist yet.

To create a directory for which no path exists, use the mkdirs( ) method. It creates both a directory and all the parents of the directory.

April 10, 2023 Smitha N. Pai, CSE Dept. 39

Page 40: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Stream Classes InputStream and OutputStream are designed for

byte streams. Reader and Writer are designed for character

streams. The byte stream classes and the character

stream classes form separate hierarchies. Use the character stream classes when working

with characters or strings, and use the byte stream classes when working with bytes or other binary objects.

April 10, 2023 Smitha N. Pai, CSE Dept. 40

Page 41: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Byte Streams The byte stream classes provide a rich

environment for handling byte-oriented I/O. A byte stream can be used with any type of

object, including binary data.

InputStream InputStream is an abstract class that defines Java’s

model of streaming byte input. All of the methods in this class will throw an

IOException on error conditions.

April 10, 2023 Smitha N. Pai, CSE Dept. 41

Page 42: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 42

Page 43: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

OutputStream OutputStream is an abstract class that defines

streaming byte output. All the methods in this class return a void value

and throw an IOException in the case of errors.

April 10, 2023 Smitha N. Pai, CSE Dept. 43

Page 44: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 44

Page 45: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileInputStream The FileInputStream class creates an InputStream

that you can use to read bytes from a file. FileInputStream(String filepath) FileInputStream(File fileObj)

They can throw a FileNotFoundException.

filepath is the full path name of a file, and fileObj is a File object that describes the file.FileInputStream f0 = new FileInputStream ("/autoexec.bat“)

File f = new File("/autoexec.bat");

FileInputStream f1 = new FileInputStream(f);

April 10, 2023 Smitha N. Pai, CSE Dept. 45

Page 46: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileInputStream FileInputStream is created, it is also opened for

reading. FileInputStream overrides six of the methods in the

abstract class InputStream. The mark( ) and reset( ) methods are not

overridden, and any attempt to use reset( ) on a FileInputStream will generate an IOException.

April 10, 2023 Smitha N. Pai, CSE Dept. 46

Page 47: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

import java.io.*;

class FileInputStreamDemo {

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

int size;

InputStream f =new FileInputStream("FileInputStreamDemo.java");

System.out.println("Total Available Bytes: " + (size = f.available()));

int n = size/40;

System.out.println("First " + n + " bytes of the file one read() at a time");

for (int i=0; i < n; i++) {

System.out.print((char) f.read());

}

April 10, 2023 Smitha N. Pai, CSE Dept. 47

Page 48: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

System.out.println("\nStill Available: " + f.available());

System.out.println("Reading the next " + n + " with one read(b[])");

byte b[] = new byte[n];

if (f.read(b) != n) {

System.err.println("couldn't read " + n + " bytes.");

}

System.out.println(new String(b, 0, n));

System.out.println("\nStill Available: " + (size = f.available()));

System.out.println("Skipping half of remaining bytes with skip()");

f.skip(size/2);

April 10, 2023 Smitha N. Pai, CSE Dept. 48

Page 49: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

System.out.println("Still Available: " + f.available());

System.out.println("Reading " + n/2 + " into the end of array");

if (f.read(b, n/2, n/2) != n/2) {

System.err.println("couldn't read " + n/2 + " bytes.");

}

System.out.println(new String(b, 0, b.length));

System.out.println("\nStill Available: " + f.available());

f.close();

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 49

Page 50: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Here is the output produced by this program:

Total Available Bytes: 1433

First 35 bytes of the file one read() at a time

// Demonstrate FileInputStream.

im

Still Available: 1398

Reading the next 35 with one read(b[])

port java.io.*;

class FileInputS

Still Available: 1363

Skipping half of remaining bytes with skip()

Still Available: 682

Reading 17 into the end of array

port java.io.*;

read(b) != n) {

S

Still Available: 665April 10, 2023 Smitha N. Pai, CSE Dept. 50

Page 51: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileOutputStream FileOutputStream creates an OutputStream that

you can use to write bytes to a file. FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append)

They can throw a FileNotFoundException or a SecurityException.

filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, the file is opened in append mode.

April 10, 2023 Smitha N. Pai, CSE Dept. 51

Page 52: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Creation of a FileOutputStream is not dependent on the file already existing.

FileOutputStream will create the file before opening it for output when you create the object.

In the case where you attempt to open a read-only file, an IOException will be thrown.

April 10, 2023 Smitha N. Pai, CSE Dept. 52

Page 53: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate FileOutputStream.

import java.io.*;

class FileOutputStreamDemo {

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

String source = "Now is the time for all good men\n"

+ " to come to the aid of their country\n"

+ " and pay their due taxes.";

byte buf[] = source.getBytes();

OutputStream f0 = new FileOutputStream("file1.txt");

for (int i=0; i < buf.length; i += 2) {

f0.write(buf[i]);

}

f0.close();

April 10, 2023 Smitha N. Pai, CSE Dept. 53

Page 54: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

OutputStream f1 = new FileOutputStream("file2.txt");

f1.write(buf);

f1.close();

OutputStream f2 = new FileOutputStream("file3.txt");

f2.write(buf,buf.length-buf.length/4,buf.length/4);

f2.close(); } } //outputFirst, file1.txt:

Nwi h iefralgo e

t oet h i ftercuty n a hi u ae.Next, file2.txt:

Now is the time for all good men

to come to the aid of their country

and pay their due taxes.Finally, file3.txt:

nd pay their due taxes.April 10, 2023 Smitha N. Pai, CSE Dept. 54

Page 55: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

/* Display a text file.

To use this program, specify the name

of the file that you want to see.

For example, to see a file called TEST.TXT,

use the following command line.

java ShowFile TEST.TXT

*/

import java.io.*;

class ShowFile {

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

{ int i;

FileInputStream fin;

April 10, 2023 Smitha N. Pai, CSE Dept. 55

Page 56: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

try {

fin = new FileInputStream(args[0]);

} catch(FileNotFoundException e) {

System.out.println("File Not Found");

return;

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Usage: ShowFile 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();

} }April 10, 2023 Smitha N. Pai, CSE Dept. 56

Page 57: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

/* Copy a text file.

To use this program, specify the name

of the source file and the destination file.

For example, to copy a file called FIRST.TXT

to a file called SECOND.TXT, use the following

command line.

java CopyFile FIRST.TXT SECOND.TXT

*/

April 10, 2023 Smitha N. Pai, CSE Dept. 57

Page 58: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

import java.io.*;

class CopyFile {

public static void main(String args[])

throws IOException {

int i;

FileInputStream fin;

FileOutputStream fout;

try {

// open input file

try {

fin = new FileInputStream(args[0]);

} catch(FileNotFoundException e) {

System.out.println("Input File Not Found");

return; }

April 10, 2023 Smitha N. Pai, CSE Dept. 58

Page 59: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// open output file

try {

fout = new FileOutputStream(args[1]);

} catch(FileNotFoundException e) {

System.out.println("Error Opening Output File");

return;

}

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Usage: CopyFile From To");

return;

}

April 10, 2023 Smitha N. Pai, CSE Dept. 59

Page 60: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Copy File

try {

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

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 60

Page 61: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

PrintStream The PrintStream class provides all of the

formatting capabilities we have been using from the System file handle, System.out PrintStream(OutputStream outputStream) PrintStream(OutputStream outputStream, boolean

flushOnNewline) where flushOnNewline controls whether Java

flushes the output stream every time a newline (\n) character is output.

April 10, 2023 Smitha N. Pai, CSE Dept. 65

Page 62: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

PrintStream If flushOnNewline is true, flushing automatically

takes place. If it is false, flushing is not automatic. The first constructor does not automatically flush. Java’s PrintStream objects support the print( )

and println( ) methods for all types, including Object.

If an argument is not a simple type, the PrintStream methods will call the object’s toString( ) method and then print the result.

April 10, 2023 Smitha N. Pai, CSE Dept. 66

Page 63: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The PrintWriter Class To write to the console use PrintWriter stream. PrintWriter is one of the character-based classes.

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called.

If flushOnNewline is true, flushing automatically takes place else if false, flushing is not automatic.

April 10, 2023 Smitha N. Pai, CSE Dept. 67

Page 64: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

PrintWriter supports the print( ) and println( ) methods for all types including Object.

If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result.

To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. PrintWriter pw = new PrintWriter(System.out, true);

April 10, 2023 Smitha N. Pai, CSE Dept. 68

Page 65: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate PrintWriter

import java.io.*;

public class PrintWriterDemo {

public static void main(String args[]) {

PrintWriter pw = new PrintWriter(System.out, true);

pw.println("This is a string");

int i = -7;

pw.println(i);

double d = 4.5e-7;

pw.println(d);

}

}

The output from this program is shown here:

This is a string

-7

4.5E-7

April 10, 2023 Smitha N. Pai, CSE Dept. 69

Page 66: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Writing Console Output PrintStream is an output stream derived from

OutputStream It implements the low-level method write( ). write( ) can be used to write to the console.

void write(int byteval) This method writes to the stream the byte

specified by byteval. byteval is declared as an integer and only the

low-order eight bits are written

April 10, 2023 Smitha N. Pai, CSE Dept. 70

Page 67: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

RandomAccessFile RandomAccessFile encapsulates a random-access

file. It implements the interfaces DataInput and

DataOutput, which define the basic I/O methods. It supports positioning requests you can position

the file pointer within the file. RandomAccessFile(File fileObj, String access)

throws FileNotFoundException RandomAccessFile(String filename, String

access)

throws FileNotFoundException

April 10, 2023 Smitha N. Pai, CSE Dept. 71

Page 68: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

access determines what type of file access is permitted. If it is “r”, then the file can be read, but not written.

If it is “rw”, then the file is opened in read-write mode.

If it is “rws”, the file is opened for read-write operations and every change to the file’s data or metadata will be immediately written to the physical device.

If it is “rwd”, the file is opened for read-write operations and every change to the file’s data will be immediately written to the physical device.

April 10, 2023 Smitha N. Pai, CSE Dept. 72

Page 69: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The method seek( ), shown here, is used to set the current position of the file pointer within the file: void seek(long newPos) throws IOException

newPos specifies the new position, in bytes, of the file pointer from the beginning of the file.

After a call to seek( ), the next read or write operation will occur at the new file position.

April 10, 2023 Smitha N. Pai, CSE Dept. 73

Page 70: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

RandomAccessFile implements the standard input and output methods, which you can use to read and write to random access files. setLength( ) void setLength(long len) throws IOException

This method sets the length of the invoking file to that specified by len.

This method can be used to lengthen or shorten a file. If the file is lengthened, the added portion is undefined.

April 10, 2023 Smitha N. Pai, CSE Dept. 74

Page 71: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Character Streams Reader

Reader is an abstract class that defines Java’s model of streaming character input.

All of the methods in this class will throw an IOException on error conditions.

Writer Writer is an abstract class that defines streaming

character output. All of the methods in this class return a void value

and throw an IOException in the case of errors.

April 10, 2023 Smitha N. Pai, CSE Dept. 75

Page 72: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The Character Streams FileReader

The FileReader class creates a Reader that you can use to read the contents of a file. Two forms: FileReader(String filePath) FileReader(File fileObj)

Methods defined by reader and writer classes follows

April 10, 2023 Smitha N. Pai, CSE Dept. 76

Page 73: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 77

Page 74: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 78

Page 75: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate FileReader.

import java.io.*;

class FileReaderDemo {

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

FileReader fr = new FileReader("FileReaderDemo.java");

BufferedReader br = new BufferedReader(fr);

String s;

while((s = br.readLine()) != null) {

System.out.println(s);

}

fr.close();

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 79

Page 76: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileWriter FileWriter creates a Writer that you can use to write to a

file. FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append)

They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is

a File object that describes the file. If append is true, then output is appended to the end of

the file.

April 10, 2023 Smitha N. Pai, CSE Dept. 80

Page 77: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileWriter will create the file before opening it for output when you create the object.

In the case where you attempt to open a read-only file, an IOException will be thrown.

April 10, 2023 Smitha N. Pai, CSE Dept. 81

Page 78: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate FileWriter.

import java.io.*;

class FileWriterDemo {

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

String source = "Now is the time for all good men\n"

+ " to come to the aid of their country\n"

+ " and pay their due taxes.";

char buffer[] = new char[source.length()];

source.getChars(0, source.length(), buffer, 0);

FileWriter f0 = new FileWriter("file1.txt");

for (int i=0; i < buffer.length; i += 2) {

f0.write(buffer[i]); }

f0.close();

April 10, 2023 Smitha N. Pai, CSE Dept. 82

Page 79: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

FileWriter f1 = new FileWriter("file2.txt");

f1.write(buffer);

f1.close();

FileWriter f2 = new FileWriter("file3.txt");

f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);

f2.close(); } }First, file1.txt:

Nwi h iefralgo e

t oet h i ftercuty n a hi u ae.Next, file2.txt:

Now is the time for all good men

to come to the aid of their country

and pay their due taxes.Finally, file3.txt:

nd pay their due taxes

April 10, 2023 Smitha N. Pai, CSE Dept. 83

Page 80: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

CharArrayReader CharArrayReader is an implementation of an

input stream that uses a character array as the source. CharArrayReader(char array[ ]) CharArrayReader(char array[ ], int start, int

numChars) Here, array is the input source.

April 10, 2023 Smitha N. Pai, CSE Dept. 84

Page 81: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate CharArrayReader.

import java.io.*;

public class CharArrayReaderDemo {

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

String tmp = "abcdefghijklmnopqrstuvwxyz";

int length = tmp.length();

char c[] = new char[length];

tmp.getChars(0, length, c, 0);

CharArrayReader input1 = new CharArrayReader(c);

CharArrayReader input2 = new CharArrayReader(c, 0, 5);

April 10, 2023 Smitha N. Pai, CSE Dept. 85

Page 82: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

int i;

System.out.println("input1 is:");

while((i = input1.read()) != -1) {

System.out.print((char)i); }

System.out.println();

System.out.println("input2 is:");

while((i = input2.read()) != -1) {

System.out.print((char)i); }

System.out.println(); } }input1 is:

abcdefghijklmnopqrstuvwxyzinput2 is:

abcde

April 10, 2023 Smitha N. Pai, CSE Dept. 86

Page 83: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

CharArrayWriter CharArrayWriter is an implementation of an output

stream that uses an array as the destination. CharArrayWriter( ) CharArrayWriter(int numChars)

The buffer is held in the buf field of CharArrayWriter. The buffer size will be increased automatically, if

needed. The number of characters held by the buffer is

contained in the count field of CharArrayWriter. Both buf and count are protected fields.

April 10, 2023 Smitha N. Pai, CSE Dept. 87

Page 84: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Demonstrate CharArrayWriter.

import java.io.*;

class CharArrayWriterDemo {

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

CharArrayWriter f = new CharArrayWriter();

String s = "This should end up in the array";

char buf[] = new char[s.length()];

s.getChars(0, s.length(), buf, 0);

f.write(buf);

System.out.println("Buffer as a string");

System.out.println(f.toString());

System.out.println("Into array");

char c[] = f.toCharArray();

April 10, 2023 Smitha N. Pai, CSE Dept. 88

Page 85: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

for (int i=0; i<c.length; i++) {

System.out.print(c[i]);

}

System.out.println("\nTo a FileWriter()");

FileWriter f2 = new FileWriter("test.txt");

f.writeTo(f2);

f2.close();

System.out.println("Doing a reset");

f.reset();

for (int i=0; i<3; i++)

f.write('X');

System.out.println(f.toString());

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 89

Page 86: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 90

Buffer as a string

This should end up in the array

Into array

This should end up in the array

To a FileWriter()

Doing a reset

XXX

Page 87: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

BufferedReader BufferedReader improves performance by

buffering input. BufferedReader(Reader inputStream) BufferedReader(Reader inputStream, int bufSize)

April 10, 2023 Smitha N. Pai, CSE Dept. 91

Page 88: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Use buffered input.

import java.io.*;

class BufferedReaderDemo {

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

String s = "This is a &copy; copyright symbol " +

"but this is &copy not.\n";

char buf[] = new char[s.length()];

s.getChars(0, s.length(), buf, 0);

CharArrayReader in = new CharArrayReader(buf);

BufferedReader f = new BufferedReader(in);

int c;

April 10, 2023 Smitha N. Pai, CSE Dept. 92

Page 89: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

boolean marked = false;

while ((c = f.read()) != -1) {

switch(c) {

case '&':

if (!marked) {

f.mark(32);

marked = true;

} else {

marked = false; }

break;

case ';':

if (marked) {

marked = false;

System.out.print("(c)");

} else

System.out.print((char) c);

break;

April 10, 2023 Smitha N. Pai, CSE Dept. 93

Page 90: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

case ' ':

if (marked) {

marked = false;

f.reset();

System.out.print("&");

} else

System.out.print((char) c);

break;

default:

if (!marked)

System.out.print((char) c);

break;

}

}

}

}

Output:

This is a (c) copyright symbol but this is &copy not.

April 10, 2023 Smitha N. Pai, CSE Dept. 94

Page 91: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

BufferedWriter A BufferedWriter is a Writer that adds a flush( )

method that can be used to ensure that data buffers are physically written to the actual output stream.

BufferedWriter can increase performance by reducing the number of times data is actually physically written to the output stream. BufferedWriter(Writer outputStream) BufferedWriter(Writer outputStream, int bufSize)

The first form creates a buffered stream using a buffer with a default size.

April 10, 2023 Smitha N. Pai, CSE Dept. 95

Page 92: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

PrintWriter PrintWriter is essentially a character-oriented version of

PrintStream. It provides the formatted output methods print( ) and println( ).

PrintWriter(OutputStream outputStream) PrintWriter(OutputStream outputStream, boolean

flushOnNewline) PrintWriter(Writer outputStream) PrintWriter(Writer outputStream, boolean flushOnNewline)

where flushOnNewline controls whether Java flushes the output stream every time println( ) is called.

April 10, 2023 Smitha N. Pai, CSE Dept. 96

Page 93: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

PrintWriter If flushOnNewline is true, flushing automatically

takes place. If false, flushing is not automatic. Java’s PrintWriter objects support the print( )

and println( ) methods for all types, including Object.

If an argument is not a simple type, the PrintWriter methods will call the object’s toString( ) method and then print out the result.

April 10, 2023 Smitha N. Pai, CSE Dept. 97

Page 94: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Using Stream I/O// A word counting utility.

import java.io.*;

class WordCount {

public static int words = 0;

public static int lines = 0;

public static int chars = 0;

public static void wc(InputStreamReader isr)

throws IOException {

int c = 0;

boolean lastWhite = true;

April 10, 2023 Smitha N. Pai, CSE Dept. 98

Page 95: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

String whiteSpace = " \t\n\r";

while ((c = isr.read()) != -1) {

// Count characters

chars++;

// Count lines

if (c == '\n') {

lines++;

}

April 10, 2023 Smitha N. Pai, CSE Dept. 99

Page 96: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Count words by detecting the start of a word

int index = whiteSpace.indexOf(c);

if(index == -1) {

if(lastWhite == true) {

++words;

}

lastWhite = false;

}

else {

lastWhite = true;

}

}

if(chars != 0) {

++lines;

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 100

Page 97: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

public static void main(String args[]) {

FileReader fr;

try {

if (args.length == 0) { // We're working with stdin

wc(new InputStreamReader(System.in));

}

else { // We're working with a list of files

for (int i = 0; i < args.length; i++) {

fr = new FileReader(args[i]);

wc(fr);

}

}

}

catch (IOException e) {

return;

}

System.out.println(lines + " " + words + " " + chars); } }

April 10, 2023 Smitha N. Pai, CSE Dept. 101

Page 98: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

The parsing process is controlled by a table and a number of flags that can be set to various states.

The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.

The character value is used to look up five possible attributes of the character: white space, alphabetic, numeric, string quote, and comment character.

April 10, 2023 Smitha N. Pai, CSE Dept. 102

Improving wc( ) Using a StreamTokenizer

Page 99: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Improving wc( ) Using a StreamTokenizer StreamTokenizer breaks up the InputStream into

tokens that are delimited by sets of characters. StreamTokenizer(Reader inStream)

inStream must be some form of Reader. To reset the default set of delimiters, we will employ

the resetSyntax( ) method – Removes delimiters The default set of delimiters is finely tuned for

tokenizing Java programs Tokens, or “words,” are any consecutive string of

visible characters delimited on both sides by whitespace.

April 10, 2023 Smitha N. Pai, CSE Dept. 103

Page 100: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF.

April 10, 2023 Smitha N. Pai, CSE Dept. 104

Page 101: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

double nval           If the current token is a number, this field contains the value of that number.

 String sval           If the current token is a word token, this field contains a string giving the characters of the word token.

static int TT_EOF           A constant indicating that the end of the stream has been read.

static int TT_EOL           A constant indicating that the end of the line has been read.

April 10, 2023 Smitha N. Pai, CSE Dept. 105

Page 102: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

static int TT_NUMBER           A constant indicating that a number token has been read.

static int TT_WORD           A constant indicating that a word token has been read.

 int ttype           After a call to the nextToken method, this field contains the type of the token just read.

April 10, 2023 Smitha N. Pai, CSE Dept. 106

Page 103: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

public int ttype For a single character token, its value is the single

character, converted to an integer. For a quoted string token its value is the quote

character. Otherwise, its value is one of the following:

TT_WORD indicates that the token is a word. TT_NUMBER indicates that the token is a

number. TT_EOL indicates that the end of line has been

read. The field can only have this value if the eolIsSignificant() method has been called with the argument true.

TT_EOF indicates that the end of the input stream has been reached.

April 10, 2023 Smitha N. Pai, CSE Dept. 107

Page 104: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

the eolIsSignificant( ) method to ensure that newline characters will be delivered as tokens, so we can count the number of lines as well as words. void eolIsSignificant(boolean eolFlag)

If eolFlag is true, the end-of-line characters are returned as tokens.

If eolFlag is false, the end-of-line characters are ignored.

The wordChars( ) method is used to specify the range of characters that can be used in words. void wordChars(int start, int end)

start and end specify the range of valid characters.

April 10, 2023 Smitha N. Pai, CSE Dept. 108

Page 105: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

The whitespace characters are specified using whitespaceChars( ). void whitespaceChars(int start, int end)

start and end specify the range of valid whitespace characters.

The next token is obtained from the input stream by calling nextToken( ). StreamTokenizer defines four int constants: TT_EOF, TT_EOL, TT_NUMBER, and TT_WORD.

April 10, 2023 Smitha N. Pai, CSE Dept. 109

Page 106: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

// Enhanced word count program that uses a StreamTokenizer

import java.io.*;

class WordCount {

public static int words=0;

public static int lines=0;

public static int chars=0;

public static void wc(Reader r) throws IOException {

StreamTokenizer tok = new StreamTokenizer(r);

tok.resetSyntax(); //Resets this tokenizer's syntax table so that all characters are "ordinary.” It removes any special significance the character has as a comment character string delimiter, white space, or number character. The parser treates it as a single-character token and sets ttype field to the character value.

tok.wordChars(33, 255);//  Specifies that all characters c in the range low <= c <= high are word constituents.

April 10, 2023 Smitha N. Pai, CSE Dept. 111

Page 107: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

tok.whitespaceChars(0, ' ');//Specifies that all characters c in the range low <= c <= high are white space characters.

tok.eolIsSignificant(true);// Determines whether or not ends of line are treated as tokens.

while (tok.nextToken() != tok.TT_EOF) {

switch (tok.ttype) {

case StreamTokenizer.TT_EOL:

lines++;

chars++;

break;

case StreamTokenizer.TT_WORD:

words++;

April 10, 2023 Smitha N. Pai, CSE Dept. 112

Page 108: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

default: // FALLSTHROUGH

chars += tok.sval.length(); break;

//If the current token is a word token, this field contains a string giving the characters of the word token. When the current token is a quoted string token, this field contains the body of the string. The current token is a word when the value of the ttype field is TT_WORD. The current token is a quoted string token when the value of the ttype field is a quote character.

} } }

April 10, 2023 Smitha N. Pai, CSE Dept. 113

Page 109: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

public static void main(String args[]) {

if (args.length == 0) { // We're working with stdin

try {

wc(new InputStreamReader(System.in));

System.out.println(lines + " " + words + " " + chars);

} catch (IOException e) {};

} else { // We're working with a list of files

int twords = 0, tchars = 0, tlines = 0;

for (int i=0; i<args.length; i++) {

try {

words = chars = lines = 0;

wc(new FileReader(args[i]));

twords += words;

tchars += chars;

tlines += lines;

System.out.println(args[i] + ": " + lines + " " + words + " " + chars); }

April 10, 2023 Smitha N. Pai, CSE Dept. 114

Page 110: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

catch (IOException e) {

System.out.println(args[i] + ": error.");

}

}

System.out.println("total: " + tlines + " " + twords + " " + tchars);

}

}

}

April 10, 2023 Smitha N. Pai, CSE Dept. 115

Page 111: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Serialization Serialization is the process of writing the state of

an object to a byte stream. This is useful when you want to save the state

of your program to a persistent storage area, such as a file.

Serialization is also needed to implement Remote Method Invocation (RMI).

April 10, 2023 Smitha N. Pai, CSE Dept. 116

Page 112: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Serialization RMI allows a Java object on one machine to

invoke a method of a Java object on a different machine.

An object may be supplied as an argument to that remote method.

The sending machine serializes the object and transmits it.

The receiving machine deserializes it.

April 10, 2023 Smitha N. Pai, CSE Dept. 117

Page 113: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Objects may also contain references to themselves.

Similarly, during the process of deserialization, all of these objects and their references are correctly restored.

April 10, 2023 Smitha N. Pai, CSE Dept. 118

Page 114: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Serializable Only an object that implements the Serializable

interface can be saved and restored by the serialization facilities.

The Serializable interface defines no members. It is used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also

serializable. Variables that are declared as transient are not saved

by the serialization facilities. Also, static variables are not saved.

April 10, 2023 Smitha N. Pai, CSE Dept. 119

Page 115: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Externalizable It may be desirable to use compression or

encryption techniques. The Externalizable interface is designed for

these situations. The Externalizable interface defines these two

methods: void readExternal(ObjectInput inStream)

throws IOException, ClassNotFoundException void writeExternal(ObjectOutput outStream)

throws IOException

April 10, 2023 Smitha N. Pai, CSE Dept. 120

Page 116: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Externalizable inStream is the byte stream from which the

object is to be read, and outStream is the byte stream to which the

object is to be written.

April 10, 2023 Smitha N. Pai, CSE Dept. 121

Page 117: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

ObjectOutput The ObjectOutput interface extends the

DataOutput interface and supports object Serialization

All of these methods will throw an IOException on error conditions.

April 10, 2023 Smitha N. Pai, CSE Dept. 122

Page 118: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 123

Page 119: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

ObjectInputStream The ObjectInputStream class extends the

InputStream class and implements the ObjectInput interface.

ObjectInputStream is responsible for reading objects from a stream. ObjectInputStream(InputStream inStream)

throws IOException, StreamCorruptedException inStream is the input stream from which

serialized objects should be read.

April 10, 2023 Smitha N. Pai, CSE Dept. 124

Page 120: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 125

Page 121: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 126

Page 122: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

A Serialization Exampleimport java.io.*;

public class SerializationDemo {

public static void main(String args[]) {

// Object serialization

try {

MyClass object1 = new MyClass("Hello", -7, 2.7e10);

System.out.println("object1: " + object1);

FileOutputStream fos = new FileOutputStream("serial");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(object1);

oos.flush();

oos.close();

}

catch(Exception e) {

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

System.exit(0);

}

April 10, 2023 Smitha N. Pai, CSE Dept. 127

Page 123: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

April 10, 2023 Smitha N. Pai, CSE Dept. 128

// Object deserializationtry {MyClass object2;FileInputStream fis = new FileInputStream("serial");ObjectInputStream ois = new ObjectInputStream(fis);object2 = (MyClass)ois.readObject();ois.close();System.out.println("object2: " + object2);}catch(Exception e) {System.out.println("Exception during deserialization: " + e);System.exit(0);}}}

Page 124: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

class MyClass implements Serializable {

String s;

int i;

double d;

public MyClass(String s, int i, double d) {

this.s = s;

this.i = i;

this.d = d;

}

public String toString() {

return "s=" + s + "; i=" + i + "; d=" + d;

} }

This program demonstrates that the instance variables of

object1 and object2 are identical. The output is shown here:

object1: s=Hello; i=-7; d=2.7E10

object2: s=Hello; i=-7; d=2.7E10

April 10, 2023 Smitha N. Pai, CSE Dept. 129

Page 125: I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1

Stream Benefits The streaming interface to I/O in Java provides a

clean abstraction for a complex task. The composition of the filtered stream classes

allows to dynamically build the custom streaming interface to suit data transfer requirements.

Java programs written to adhere to the abstract, high-level InputStream, OutputStream, Reader, and Writer classes will function properly in the future even when new and improved concrete stream classes are invented.

April 10, 2023 Smitha N. Pai, CSE Dept. 130