Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed...

Preview:

Citation preview

Java IOJava IO

Why IO ?Why IO ?

Without I/O, your program is a closed box.Without I/O, your program is a closed box. I/O gives your Java program access to your I/O gives your Java program access to your

hard drive, the Web, and the rest of the hard drive, the Web, and the rest of the Internet.Internet.

StreamStream

A A streamstream is a path of communication is a path of communication between a source of information and a between a source of information and a destination.destination.

If we’re the source, the If we’re the source, the streamstream is an output is an output stream.stream.

If we’re the destination, the If we’re the destination, the streamstream is an is an input stream.input stream.

Standard StreamsStandard Streams Java provides.Java provides.

System.InSystem.In -KB.-KB.

System.OutSystem.Out -monitor.-monitor.

System.ErrSystem.Err -monitor.-monitor. It is possible to redirect a program’s input It is possible to redirect a program’s input

stream so that it comes from a file.stream so that it comes from a file. Having a separate error stream allows Having a separate error stream allows

programs to display error messages even programs to display error messages even when the standard output stream has been when the standard output stream has been redirected.redirected.

Streams Vs Readers/writersStreams Vs Readers/writers

Generalized communication mechanisms.Generalized communication mechanisms. Streams are byte oriented.Streams are byte oriented. Readers\Writers are character (Unicode) Readers\Writers are character (Unicode)

oriented.oriented.

FileInputStream FileInputStream & &

FileOutputStreamFileOutputStream

Two of the most useful things you can do Two of the most useful things you can do with data is send and receive it to and from with data is send and receive it to and from the hard drive.the hard drive.

FileOutputStream writes data into files. FileOutputStream writes data into files. FileInputStream reads data from files.FileInputStream reads data from files.

FileOutputStream can create a new file and FileOutputStream can create a new file and write the data into it.write the data into it.

ByteArrayOutputStreamByteArrayOutputStream&&

ByteArrayInputStreamByteArrayInputStream ByteArrayOutputStream : To store your ByteArrayOutputStream : To store your

array of bytes into your computer’s local array of bytes into your computer’s local memory.memory.

ByteArrayInputStream : To retrieve an ByteArrayInputStream : To retrieve an array of bytes from your computer’s local array of bytes from your computer’s local memory.memory.

Used for complex entities.Used for complex entities.

Buffered Reads & Buffered WritesBuffered Reads & Buffered Writes BufferedInputStream—Used for reading BufferedInputStream—Used for reading

large amounts of data, by buffering input large amounts of data, by buffering input for efficiency.for efficiency.

BufferedOutputStream—Used for writing BufferedOutputStream—Used for writing out data in large blocks, using buffers for out data in large blocks, using buffers for efficiency.efficiency.

They buffer input/output so bytes of data They buffer input/output so bytes of data can be read/written from/to devices in can be read/written from/to devices in larger groups.larger groups.

The flush() method causes any buffered The flush() method causes any buffered data to be immediately written to the data to be immediately written to the output stream.output stream.

Character IOCharacter IO

If you need to output characters, use a If you need to output characters, use a Writer rather than an OutputStream.Writer rather than an OutputStream.

Readers work better with 16-bit chars, and Readers work better with 16-bit chars, and are designed for Unicode.are designed for Unicode.

Use Readers and Writers to Support Use Readers and Writers to Support Internationalization. We should write Internationalization. We should write Unicode, rather than ASCII.Unicode, rather than ASCII.

Reading LinesReading Lines

Character based streams give you the Character based streams give you the flexibility by allowing you to read lines of flexibility by allowing you to read lines of text terminated by carriage return.text terminated by carriage return.

readLine( )readLine( ) method of method of BufferedReaderBufferedReader class class provides this capability.provides this capability.

Display FormattingDisplay Formatting PrintWriterPrintWriter class is the character -stream class class is the character -stream class

corresponding to the corresponding to the PrintStreamPrintStream byte-stream byte-stream class.class.

This should be used to generate the textual This should be used to generate the textual output for users.output for users.

print( )print( ) and and println( )println( ) methods of methods of PrintWriterPrintWriter class accept primitive values and objects.class accept primitive values and objects.

flush( )flush( ) method suspends processing until the method suspends processing until the output is delivered.output is delivered.

You can use automatic flushing specifying You can use automatic flushing specifying truetrue in the constructor.in the constructor.

Platform Independent Data Platform Independent Data FormattingFormatting

A collection of methods of A collection of methods of DataInputStream DataInputStream and and DataOutputStreamDataOutputStream classes supports platform independent data classes supports platform independent data formatting.formatting.

These methods translate the internal coding These methods translate the internal coding of java’s primitive types into sequence of of java’s primitive types into sequence of bytes that can be read and written.bytes that can be read and written.

Methods:Methods: Boolean readBoolean( )Boolean readBoolean( ) Byte readByte( )Byte readByte( ) Char readChar( )Char readChar( ) Float readFloat( )Float readFloat( ) int ReadInt( )int ReadInt( ) String readLine( )String readLine( ) Long readLong( )Long readLong( ) Short readShort( )Short readShort( ) String readUTF( ) -read a unicode stringString readUTF( ) -read a unicode string Void writeBoolean(boolean v)Void writeBoolean(boolean v)

……and corresponding write methods in the and corresponding write methods in the DataOutputStream class.DataOutputStream class.

Subclasses of Subclasses of InputStreamInputStream may be wrapped may be wrapped within a within a DataInputStrean.DataInputStrean.

In fact, it is possible to wrapIn fact, it is possible to wrap BufferedInput BufferedInput stream.stream.

File ObjectFile Object File File object provides a number of methods to manipulate object provides a number of methods to manipulate

files and directories.files and directories. File can refer either a directory or a file, using a relative File can refer either a directory or a file, using a relative

or absolute path.or absolute path. Constructors:Constructors:

File(string path).File(string path).

File(string path, string filename).File(string path, string filename).

File(file path, string filename).File(file path, string filename).

If path is not null , filename interpreted as relative path.If path is not null , filename interpreted as relative path.

Methods:Methods:

Boolean canRead( )Boolean canRead( )

Boolean canWrite( )Boolean canWrite( )

Boolean delete( )Boolean delete( )

Boolean equals(object obj)Boolean equals(object obj)

Boolean exists( )Boolean exists( )

String getAbsolutePath( )String getAbsolutePath( )

String getName( )String getName( )

String getParent( )String getParent( )

String getPath( )String getPath( )

Boolean isAbsolute( )Boolean isAbsolute( )

Boolean isDirectory( )Boolean isDirectory( )

Boolean isFile( )Boolean isFile( )

Long lastModified( )Long lastModified( )

Long length( )Long length( )

String[ ] list( )String[ ] list( )

Boolean mkdir( )Boolean mkdir( )

Boolean mkdirs( )Boolean mkdirs( )

Boolean renameTo(file dest)Boolean renameTo(file dest)

Fields:Fields:

String pathSeparatorString pathSeparator

Char pathSeparatorCharChar pathSeparatorChar

String separatorString separator

Char separatorCharChar separatorChar

RandomAccessFilesRandomAccessFiles

RandomAccessFiles RandomAccessFiles class can be used for class can be used for both input and output to a single file.both input and output to a single file.

It provides similar platform independent It provides similar platform independent formatting methods as the formatting methods as the DataInputStreamDataInputStream class.class.

RandomAccessFile theFile = new RandomAccessFile theFile = new RandomAccessFile(“Test.text”, “rw”);RandomAccessFile(“Test.text”, “rw”);

The constructor has two arguments:The constructor has two arguments:

1.1. The first argument specifies the file. The first argument specifies the file.

2.2. The second specifies as ‘ The second specifies as ‘r’r’ read only, ‘ read only, ‘w’w’ write only or ‘write only or ‘rw’rw’ both. both.

If the specified file does not exists, it is If the specified file does not exists, it is automatically created.automatically created.

It is possible to direct a It is possible to direct a RandomAccessFile RandomAccessFile to read or write beginning at any position to read or write beginning at any position within a file, by the use of a within a file, by the use of a seek( )seek( ) method. method.

You specify the byte-offset from the You specify the byte-offset from the beginning of file with a beginning of file with a longlong..

File DialogsFile Dialogs

File dialog class makes it possible to write File dialog class makes it possible to write programs platform independent, while still programs platform independent, while still using operating system specific dialogs.using operating system specific dialogs.

File dialog class helps make it easy to build File dialog class helps make it easy to build programs that let the user navigate the file programs that let the user navigate the file system and open or saves files.system and open or saves files.

Constructors:Constructors:

FileDialog(Frame parent, String title)FileDialog(Frame parent, String title)

Defaults to FileDialog.LOAD for modeDefaults to FileDialog.LOAD for mode

FileDialog(Frame parent, String title, int FileDialog(Frame parent, String title, int mode)mode)

First argument frame that owns the dialogFirst argument frame that owns the dialog

Second argument specifies the titleSecond argument specifies the title

Third argument specifies the mode that the Third argument specifies the mode that the dialog uses.LOAD and SAVEdialog uses.LOAD and SAVE

Java NetworkingJava Networking

Layers of NetworkLayers of Network

NetworkingNetworking

The simplest way to create a network aware The simplest way to create a network aware java program is to use the URL class.java program is to use the URL class.

URL allows you to explicitly locate and name URL allows you to explicitly locate and name any document existing anywhere on the www.any document existing anywhere on the www.

URL theConnection = new URL theConnection = new URL(“http://www.JavaSoft.Com”);URL(“http://www.JavaSoft.Com”);

Once you have created an URL class, a Once you have created an URL class, a plethora of methods to get the content of the plethora of methods to get the content of the document and to perform other useful document and to perform other useful operations.operations.

Methods.Methods. Boolean equals(Object obj).Boolean equals(Object obj).

Object getContent( )Object getContent( ) String getFile( )String getFile( ) String getHost( )String getHost( ) String getPort( )String getPort( ) String getProtocol( )String getProtocol( ) String getRef( )String getRef( ) URLConnection openConnection( )URLConnection openConnection( ) InputStream openStream( )InputStream openStream( ) Boolean sameFile(URL doc)Boolean sameFile(URL doc)

URLConnectionURLConnection

URLConnection class allows you to get URLConnection class allows you to get information about documents that are information about documents that are referenced by URL objects.referenced by URL objects.

Use openConnection( ) method of URL Use openConnection( ) method of URL class to get the URLConnection object. class to get the URLConnection object.

Methods:Methods: Void connect( )Void connect( ) Object getContent( )Object getContent( ) String getContentEncoding( )String getContentEncoding( ) int getContentLength( )int getContentLength( ) String getContentType( )String getContentType( ) Long getExpiration( )Long getExpiration( )

URL getURL().URL getURL(). InputStream getInputStream().InputStream getInputStream(). OutputStream getOutputStream().OutputStream getOutputStream(). Void setDoInput(boolean value).Void setDoInput(boolean value). Void setDoOutput(boolean value). Void setDoOutput(boolean value).

SocketsSockets

Sockets are streams of data that can flow Sockets are streams of data that can flow between networked computers.between networked computers.

Java has facility to work directly with Java has facility to work directly with sockets.sockets.

Socket has two forms of identification:Socket has two forms of identification: Host and port.Host and port. This allows each host to have a number of This allows each host to have a number of

sockets in operation, distinguished by its sockets in operation, distinguished by its port number.port number.

One called One called serverserver and the other called and the other called clientclient..

Client requests data and the server supplies Client requests data and the server supplies it.it.

ServerSocketsServerSockets

ServerSocketServerSocket class is used to create a server class is used to create a server application that listens on a specified port for application that listens on a specified port for a client requesting service.a client requesting service.

To create a To create a ServerSocketServerSocket object, you use a object, you use a constructor that takes port number as an constructor that takes port number as an integer argument.integer argument.

Accept( )Accept( ) method can be used to obtain method can be used to obtain socket object for private conversation socket object for private conversation between the server and the client.between the server and the client.

Methods:Methods:

T accept( ).T accept( ). Void close( ).Void close( ). InetAddress getInetAddress( ) -InetAddress getInetAddress( ) - get the IP get the IP

address of the client.address of the client. int getLocalPort( ) -int getLocalPort( ) - return the local port on return the local port on

which the which the ServerSocketServerSocket is listening. is listening.

InetAddress ClassInetAddress Class

Every machine connected to internet has a Every machine connected to internet has a unique address, called IP address.unique address, called IP address.

InetAddress object is retrieved by use of the InetAddress object is retrieved by use of the ServerSocket class’s getInetAddress( ) ServerSocket class’s getInetAddress( ) method.method.

InetAddress class provides several class InetAddress class provides several class methods that allow you to retrieve an methods that allow you to retrieve an InetAddress object.InetAddress object.

Class methods:Class methods: InetAddress[ ] getAllByName(string host)InetAddress[ ] getAllByName(string host) InetAddress getByName(string host)InetAddress getByName(string host) InetAddress getLocalHost( )InetAddress getLocalHost( ) Methods:Methods: Byte[ ] getAddress( )Byte[ ] getAddress( ) String getHostName( )String getHostName( )

Socket ClassSocket Class

The Socket class is used by the server and The Socket class is used by the server and the client to converse.the client to converse.

The Socket object is returned by the The Socket object is returned by the accept()accept() method of the method of the ServerSocketServerSocket class. class.

Constructors can also be used to create the Constructors can also be used to create the Socket class.Socket class.

Socket(String host, int port).Socket(String host, int port). Socket(InetAddress ipNumber, int port).Socket(InetAddress ipNumber, int port).

Methods:Methods: Void close( ).Void close( ). InetAddress getInetAddress( ).InetAddress getInetAddress( ). InputStream getInputStream( ).InputStream getInputStream( ). int getLocalPort( ).int getLocalPort( ). OutputStream getOutputStream( ).OutputStream getOutputStream( ). int getPort( ).int getPort( ).

………….……………….End…………...………....……………….End…………...………...

Methods:Methods:

String getDirectory( )String getDirectory( )

String getFile( )String getFile( )

int getMode( )int getMode( )

Void setDirectory(string dir)Void setDirectory(string dir)

Void setFile(string file)Void setFile(string file)

Void setFilenameFilter(FilenameFilter flt)Void setFilenameFilter(FilenameFilter flt)

Recommended