• No results found

08_IO in java.pdf

N/A
N/A
Protected

Academic year: 2020

Share "08_IO in java.pdf"

Copied!
52
0
0

Loading.... (view fulltext now)

Full text

(1)

I/O in java

(2)

Java IO Classes

• Java I/O is based on a class hierarchy.

• Base classes are used to describe the basic functionality required.

• Derived classes provided the functionality for specific kinds of I/O environments.

2

(3)

I/O Stream

Stream A stream is an abstraction that either

produces or consumes information.

Input Streamreads or consumes information

Input Stream Sourcekeyboard or file

Output Stream writes or produces information

Output Stream DestinationsMonitor or file

(4)

Some Abstract Base Classes

InputStream

– for reading a stream of bytes

OutputStream

– for writing a stream of bytes

Reader

– reading a stream of characters

Writer

– writing a stream of characters.

Nihar Ranjan Roy 4

Byte Oriented

(5)

Class

OutputStream

• All

byte

stream writers

are based on the class

OutputStream

(they extend

OutputStream

)

• Some of the methods:

– void write(int b) throws IOException – void write(byte[] b) throws IOException – void flush() throws IOException

– void close() throws IOException

(6)

throws IOException

• Everything here can throw an

IOException

• If you use any of these methods, you must

catch

IOException

(or

Exception

).

IOException

6

(7)

Class

Reader

• All

character

stream

readers are based on

the class

Reader

(they extend

Reader

)

• Some of the methods:

– int read()

– int read(char[] cbuf) – boolean ready()

– void close()

(8)

Class

Writer

• All character stream writers are based on the

class Writer (they extend Writer)

• Some of the methods:

– void write(int c)

– void write(char[] cbuf) – void write(String str) – void flush()

– void close()

(9)

Abstract Classes

• You can't create an InputStream object!

– or OutputStream or Reader or Writer

• You create some object of a derived class

– a specific kind of InputStream object, perhaps a FileInputStream

– but your code can be written to work with any kind of

InputStream

(10)

System.out

System.out is actually a kind of OutputStream:

– it's a PrintStream object, but you don't need to know that to

use it as an OutputStream

OutputStream stdout = System.out; stdout.write(104); // ASCII 'h'

stdout.flush();

(11)

IOExceptions!

public static void main(String[] args) { OutputStream stdout = System.out;

try {

stdout.write(104); // 'h' stdout.write(105); // 'i' stdout.write(10); // '\n'

} catch (IOException e) { e.printStackTrace(); }

}

(12)

Another way…

public static void main(String[] args)

throws IOException {

OutputStream stdout = System.out; stdout.write(104); // 'h'

stdout.write(105); // 'i' stdout.write(10); // '\n' }

(13)

System.in

System.in

is a type of

InputStream

byte[] b = new byte[10];

InputStream stdin = System.in; stdin.read(b);

(14)

Character Streams

• Remember that Java supports UNICODE!

– support for non-ASCII characters.

• Java also supports ASCII (obviously).

• BUT – since characters are not necessarily a single byte – we need more than byte streams.

(15)

InputStreamReader

• An InputStreamReader is a bridge from byte streams to

character streams.

– You need to have an InputStream to feed the InputStreamReader.

• Each call to InputStreamReader.read() returns one char,

but may read multiple bytes from the InputStream.

(16)

InputStreamReader

attached to

stdin

InputStreamReader isr = new

InputStreamReader( System.in );

char c;

c = (char) isr.read(); System.out.write( c);

(17)

BufferedReader

• A type of

Reader

that does internal buffering.

– more efficient.

• Provides everything from

Reader

, plus:

String readLine()

– reads up to '\n’

String returned does not include the line termination char(s).

(18)

Attaching a

BufferedReader

to stdin

InputStreamReader isr = new

InputStreamReader(System.in);

BufferedReader bf = new BufferedReader(isr);

String foo = bf.readLine();

(19)

Character Stream Output

OutputStreamWriter: a bridge (converts from characters

to byte stream).

BufferedWriter: efficient Writer.

BufferedWriter bw =

new BufferedWriter(

new OutputStreamWriter ( System.out ) );

(20)

File Handling

(21)

Create a file object

package required is Import java.io.*;

File inFile=new File(“C:\\abc.dat”);

Or

File inFile=new File(“c:\\myfolder”,”abc.txt”);

(22)

boolean exists() Tests whether the file or directory denoted by this abstract pathname exists.

void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.

boolean canExecute()  Tests whether the application can execute the file denoted by this abstract pathname.

boolean canRead()  Tests whether the application can read the file denoted by this abstract pathname.

boolean canWrite()  Tests whether the application can modify the file denoted by this abstract pathname.

boolean delete()  Deletes the file or directory denoted by this abstract pathname.

String getName()  Returns the name of the file or directory denoted by this abstract pathname.

String getParent() Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

(23)

boolean isDirectory()  Tests whether the file denoted by this abstract pathname is a directory.

booleanisFile()  Tests whether the file denoted by this abstract pathname is a normal file.

booleanisHidden() Tests whether the file named by this abstract pathname is a hidden file.

longlastModified()  Returns the time that the file denoted by this abstract pathname was last modified.

longlength() Returns the length of the file denoted by this abstract pathname.

boolean mkdir()  Creates the directory named by this abstract pathname.

String[] list()  Returns an array of strings naming the files and

directories in the directory denoted by this abstract pathname.

(24)

Problem

Write a program in java that

prints all the files in a

specified directory

(25)

Listing all files from a directory

File mydir=new File(“c:\\javaprgs”);

String fileList[] = mydir.list();

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

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

Nihar Ranjan Roy 25

(26)

FileInputStream

Class FileInputStream

java.lang.Object

java.io.InputStream

java.io.FileInputStream

FileInputStream is meant for reading streams

of raw bytes such as image data

FileInputStream

(

File

file)

FileInputStream

(

String

name)

(27)

Few Methods

Nihar Ranjan Roy 27

int read() 

Reads a byte of data from this input stream.

int read(byte[] b)  Reads up to b.length bytes of data from this input stream into an array of bytes.

int read(byte[] b, int off, int len)  Reads up to len bytes of data from this input stream into an array of bytes.

(28)

Problem

Write a program in java in

which the program prints its

source code.

(29)

import java.io.*;

class ReadFromFile {

public static void main(String args[])

throws IOException { int ch;

FileInputStream fo=new

FileInputStream("c:\\myJava\\ReadFromFile.java"); while((ch=fo.read())!=-1)

{ System.out.print((char)ch); }

fo.close(); }

}

(30)

Writing to a file

• Class is FileOutPutStream

• FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

Nihar Ranjan Roy 30

Constructor Summary

FileOutputStream(File file)

Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream(File file, boolean append)

Creates a file output stream to write to the file represented by the specified File object.

FileOutputStream(String name)

Creates an output file stream to write to the file with the specified name.

FileOutputStream(String name, boolean append)

(31)

Some Methods

Nihar Ranjan Roy 31

void write(byte[] b)

Writes b.length bytes from the specified byte array to this file output stream.

void write(byte[] b, int off, int len)

Writes len bytes from the specified byte array starting at offset off to this file output stream.

void write(int b)

Writes the specified byte to this file output stream.

void close()

(32)

Problem

Write a program in java to copy a

file

myCopy sourceFile DestationFile

(33)

Class FileReader

java.lang.Object

java.io.Reader

java.io.InputStreamReader

java.io.FileReader

FileReader is meant for reading streams of

characters. For reading streams of raw bytes, consider using a FileInputStream.

Constructor Summary

FileReader ( File file)

FileReader ( String fileName)

(34)

Print the Source Code using FileReader

import java.io.*;

class FileReaderTest

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

FileReader fr=new FileReader("FileReaderTest.java"); BufferedReader br=new BufferedReader(fr);

String str=null;

while((str=br.readLine())!=null) {System.out.println(str); }

} }

(35)

Class FileWriter

java.lang.Object java.io.Writer

java.io.OutputStreamWriter

java.io.FileWriter

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

Constructor Summary

FileWriter(File file)

FileWriter(File file, boolean append)

FileWriter(String fileName)

FileWriter(String fileName, boolean append)

(36)

Problem

Write a program in java that asks the use to enter something about him. What ever the user enters it should be stored in to a file.

(37)

Nihar Ranjan Roy 37

import java.io.*;

class FileWriterTest

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

FileWriter fw=new FileWriter("FileWriter.dat"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int ch;

System.out.println("Please enter something about u"); while((ch=br.read())!=-1)

{ fw.write(ch);

}

fw.close();

System.out.println("Done Successfully"); }

(38)

DataOutputStream

DataOutputStream object

defines the methods used to write primitive data types

to output streams

Constructor Summary

DataOutputStream( OutputStream out)

Creates a new data output stream to write data to the specified underlying output stream.

(39)

Nihar Ranjan Roy 39

void writeBoolean(boolean v) void writeByte(int v)

void writeBytes( String s) void writeChar(int v)

void writeChars( String s) void writeDouble(double v) void writeFloat(float v)

void writeInt(int v)

(40)

Writing Primitives Data types to file

import java.io.*;

class PrimitiveWrite

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

DataOutputStream dos=

new DataOutputStream(

new FileOutputStream("Primitive.dat")); dos.writeInt(23);

dos.writeBoolean(true); dos.close();

} }

(41)

DataInputStream

A DataInputStream lets an application read primitive Java data types from an underlying input stream in a machine-independent way

Constructor Summary

DataInputStream ( InputStream in)

Creates a DataInputStream that uses the specified underlying InputStream.

(42)

Nihar Ranjan Roy 42

boolean readBoolean() byte readByte()

char readChar() double readDouble() float readFloat() int readInt() long readLong() short readShort()

(43)

Use of DataInputStream

Nihar Ranjan Roy 43

import java.io.*;

class PrimitiveRead {

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

DataInputStream dis=

new DataInputStream(

new FileInputStream("Primitive.dat")); System.out.println(dis.readInt());

System.out.println(dis.readBoolean()); dis.close();

(44)

Problem

Write a program in java that accepts students details NameString

Rollint

stores them to a file “student.dat”

(45)

Writing objects to file

Nihar Ranjan Roy 45

class Student implements Serializable {

String name; int roll;

(46)

Writing objects to file

Nihar Ranjan Roy 46

import java.io.*; class writeObject {

public static void main(String args[]) throws Exception {Student st=new Student("Nihar",143);

ObjectOutputStream oos=

new ObjectOutputStream(

new FileOutputStream("Object.dat"));

oos.writeObject(st);

System.out.println("Written Successfully"); oos.close();

(47)

Reading objects from file

Nihar Ranjan Roy 47

import java.io.*; class readObject {

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

ObjectInputStream ois=

new ObjectInputStream(

(48)

RandomAccessFile

• RandomAccessFile in java enables us to read and

write bytes, text and java data types to any location in a file.

• The term random means data can be written or read from random location within a file.

• This class also provides permissions like read and

write and allows files to be accessed in read only and read write mode.

(49)

• Two ways to create the file

RandomAccessFile(File name,String mode) or

RandomAccessFile(String pathname,String mode)

Modes

”r” read only

”rw” read and write.

We can read or write the primitive data types through readXXX() and writeXXX() methods

(50)

Nihar Ranjan Roy 50

class randomAccessFile {

(51)

Sequence InputStream

A SequenceInputStream represents the logical concatenation of multiple input streams.

It starts out with an ordered collection of input

streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the

contained input streams.

SequenceInputStream( InputStream s1, InputStream s2)

(52)

Problem

Write a program in java that takes two file names as command prompts and reads the files in the same order once the first file is finished it starts reading the second one.

Nihar Ranjan Roy 52

HINT

FileInputStream f1=new FileInputStream(args[0]) FileInputStream f2=new FileInputStream(args[1])

SequenceInputStream sis=new SequenceInputStream(f1,f2);

References

Related documents

See, e.g., In re Sage Realty Corp., 91 N.Y.2d 30, 35 (NY 1997) (“We conclude that the majority position, as adopted in the final draft of the American Law Institute Restatement

Keywords: Intimate partner violence, sexual assault, dating violence, domestic violence, depression, posttraumatic stress disorder, physical injury, education, prevention,

Effectiveness of the Link Crew transition program was determined by the program's impact on transitioning grade nine students at High School A: grade point average, school

Neo Cortex Remastered (Cortex Strikes Back).png]]..

This project (Appendix D) aims to introduce a practical guide with a modern look enabling beginners and especially graphic design students and type designers to

In the Third District, the number of borrowers rose from just over 1.1 million (11.5 percent of the CCP) at the start of 2005 to just under 1.8 million (17.5 percent of the CCP)

Hence we have character stream that java is one last modified time i have a file path may writting to a file java program receives data..

• 0-19 points for students who show no active participation, who do not participate in group discussions, are