Java 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 hard.

Slides:



Advertisements
Similar presentations
1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
Advertisements

Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Java Sockets Source:
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Networking Support In Java 2 Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
COMP1681 / SE15 Introduction to Programming
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Dynamic Arrays Dynamic arrays are arrays that are re- allocated to a larger size. –See Eck Section 8.3 for details. –For instance, what happens with the.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
DBI Representation and Management of Data on the Internet.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
A stream is a sequence of data. A stream is a flowing sequence of characters.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
Network Programming with Java java.net.InetAddress: public static void main(String[] args) throws UnknownHostException { InetAddress localAddress = InetAddress.getLocalHost();
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
Java IO Exploring the java.io package and living to talk about it.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Chapter 10: I/O Streams Input Streams Output Streams
The Java IO System Different kinds of IO Different kinds of operations
Fundamental of Java Programming
IO in java.
Sequential files creation & writing
Java.net CS-328 Dick Steflik.
IO in java.
Source: Java Sockets Source:
OO Design and Programming II I/O: Reading and Writing
Object Writing in files
University of Central Florida COP 3330 Object Oriented Programming
Network Programming Introduction
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
NETWORK PROGRAMMING CNET 441
Network Programming Introduction
I/O Basics.
Sockets and URLs 17-Sep-18.
Chapter 13: File Input and Output
Programming in Java Files and I/O Streams
Streams and File I/O Chapter 9 Chapter 9.
Sockets and URLs 13-Nov-18.
URL in Java C343 Lab (Week 13).
Networking.
Sockets and URLs 3-Dec-18.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
Presentation transcript:

Java 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 hard drive, the Web, and the rest of the Internet. I/O gives your Java program access to your hard drive, the Web, and the rest of the Internet.

Stream A stream is a path of communication between a source of information and a destination. A stream is a path of communication between a source of information and a destination. If we’re the source, the stream is an output stream. If we’re the source, the stream is an output stream. If we’re the destination, the stream is an input stream. If we’re the destination, the stream is an input stream.

Standard Streams Java provides. Java provides. System.In-KB. System.Out-monitor. System.Err-monitor. It is possible to redirect a program’s input stream so that it comes from a file. It is possible to redirect a program’s input stream so that it comes from a file. Having a separate error stream allows programs to display error messages even when the standard output stream has been redirected. Having a separate error stream allows programs to display error messages even when the standard output stream has been redirected.

Streams Vs Readers/writers Generalized communication mechanisms.  Streams are byte oriented.  Readers\Writers are character (Unicode) oriented.

FileInputStream & FileOutputStream Two of the most useful things you can do with data is send and receive it to and from the hard drive. Two of the most useful things you can do with data is send and receive it to and from the hard drive. FileOutputStream writes data into files. FileInputStream reads data from files. FileOutputStream writes data into files. FileInputStream reads data from files. FileOutputStream can create a new file and write the data into it. FileOutputStream can create a new file and write the data into it.

ByteArrayOutputStream & ByteArrayInputStream ByteArrayOutputStream : To store your array of bytes into your computer’s local memory. ByteArrayOutputStream : To store your array of bytes into your computer’s local memory. ByteArrayInputStream : To retrieve an array of bytes from your computer’s local memory. ByteArrayInputStream : To retrieve an array of bytes from your computer’s local memory. Used for complex entities. Used for complex entities.

Buffered Reads & Buffered Writes BufferedInputStream—Used for reading large amounts of data, by buffering input for efficiency. BufferedInputStream—Used for reading large amounts of data, by buffering input for efficiency. BufferedOutputStream—Used for writing out data in large blocks, using buffers for efficiency. BufferedOutputStream—Used for writing out data in large blocks, using buffers for efficiency. They buffer input/output so bytes of data can be read/written from/to devices in larger groups. They buffer input/output so bytes of data can be read/written from/to devices in larger groups. The flush() method causes any buffered data to be immediately written to the output stream. The flush() method causes any buffered data to be immediately written to the output stream.

Character IO If you need to output characters, use a Writer rather than an OutputStream. If you need to output characters, use a Writer rather than an OutputStream. Readers work better with 16-bit chars, and are designed for Unicode. Readers work better with 16-bit chars, and are designed for Unicode. Use Readers and Writers to Support Internationalization. We should write Unicode, rather than ASCII. Use Readers and Writers to Support Internationalization. We should write Unicode, rather than ASCII.

Reading Lines Character based streams give you the flexibility by allowing you to read lines of text terminated by carriage return. Character based streams give you the flexibility by allowing you to read lines of text terminated by carriage return. readLine( ) method of BufferedReader class provides this capability. readLine( ) method of BufferedReader class provides this capability.

Display Formatting PrintWriter class is the character -stream class corresponding to the PrintStream byte-stream class. PrintWriter class is the character -stream class corresponding to the PrintStream byte-stream class. This should be used to generate the textual output for users. This should be used to generate the textual output for users. print( ) and println( ) methods of PrintWriter class accept primitive values and objects. print( ) and println( ) methods of PrintWriter class accept primitive values and objects. flush( ) method suspends processing until the output is delivered. flush( ) method suspends processing until the output is delivered. You can use automatic flushing specifying true in the constructor. You can use automatic flushing specifying true in the constructor.

Platform Independent Data Formatting A collection of methods of DataInputStream and DataOutputStream classes supports platform independent data formatting. A collection of methods of DataInputStream and DataOutputStream classes supports platform independent data formatting. These methods translate the internal coding of java’s primitive types into sequence of bytes that can be read and written. These methods translate the internal coding of java’s primitive types into sequence of bytes that can be read and written.

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 string String readUTF( ) -read a unicode string Void writeBoolean(boolean v) Void writeBoolean(boolean v)

…and corresponding write methods in the DataOutputStream class. Subclasses of InputStream may be wrapped within a DataInputStrean. Subclasses of InputStream may be wrapped within a DataInputStrean. In fact, it is possible to wrap BufferedInput stream. In fact, it is possible to wrap BufferedInput stream.

File Object File object provides a number of methods to manipulate files and directories. File object provides a number of methods to manipulate files and directories. File can refer either a directory or a file, using a relative or absolute path. File can refer either a directory or a file, using a relative or absolute path. Constructors: Constructors: File(string path). File(string path, string filename). File(file path, string filename). If path is not null, filename interpreted as relative path.

Methods: Methods: Boolean canRead( ) Boolean canWrite( ) Boolean delete( ) Boolean equals(object obj) Boolean exists( ) String getAbsolutePath( ) String getName( ) String getParent( ) String getPath( ) String getPath( )

Boolean isAbsolute( ) Boolean isDirectory( ) Boolean isDirectory( ) Boolean isFile( ) Boolean isFile( ) Long lastModified( ) Long length( ) String[ ] list( ) Boolean mkdir( ) Boolean mkdirs( ) Boolean mkdirs( ) Boolean renameTo(file dest)

Fields: Fields: String pathSeparator String pathSeparator Char pathSeparatorChar String separator Char separatorChar

RandomAccessFiles RandomAccessFiles class can be used for both input and output to a single file. RandomAccessFiles class can be used for both input and output to a single file. It provides similar platform independent formatting methods as the DataInputStream class. It provides similar platform independent formatting methods as the DataInputStream class. RandomAccessFile theFile = new RandomAccessFile(“Test.text”, “rw”); RandomAccessFile theFile = new RandomAccessFile(“Test.text”, “rw”);

The constructor has two arguments: The constructor has two arguments: 1. The first argument specifies the file. 2. The second specifies as ‘r’ read only, ‘w’ write only or ‘rw’ both. If the specified file does not exists, it is automatically created. If the specified file does not exists, it is automatically created. It is possible to direct a RandomAccessFile to read or write beginning at any position within a file, by the use of a seek( ) method. It is possible to direct a RandomAccessFile to read or write beginning at any position within a file, by the use of a seek( ) method. You specify the byte-offset from the beginning of file with a long. You specify the byte-offset from the beginning of file with a long.

File Dialogs File dialog class makes it possible to write programs platform independent, while still using operating system specific dialogs. File dialog class makes it possible to write programs platform independent, while still using operating system specific dialogs. File dialog class helps make it easy to build programs that let the user navigate the file system and open or saves files. File dialog class helps make it easy to build programs that let the user navigate the file system and open or saves files.

Constructors: Constructors: FileDialog(Frame parent, String title) Defaults to FileDialog.LOAD for mode FileDialog(Frame parent, String title, int mode) FileDialog(Frame parent, String title, int mode) First argument frame that owns the dialog Second argument specifies the title Third argument specifies the mode that the dialog uses.LOAD and SAVE

Java Networking

Layers of Network

Networking The simplest way to create a network aware java program is to use the URL class. The simplest way to create a network aware java program is to use the URL class. URL allows you to explicitly locate and name any document existing anywhere on the www. URL allows you to explicitly locate and name any document existing anywhere on the www.

URL theConnection = new URL(“ URL theConnection = new URL(“ Once you have created an URL class, a plethora of methods to get the content of the document and to perform other useful operations. Once you have created an URL class, a plethora of methods to get the content of the document and to perform other useful 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)

URLConnection URLConnection class allows you to get information about documents that are referenced by URL objects. URLConnection class allows you to get information about documents that are referenced by URL objects. Use openConnection( ) method of URL class to get the URLConnection object. Use openConnection( ) method of URL class to get the URLConnection object.

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

Sockets Sockets are streams of data that can flow between networked computers. Sockets are streams of data that can flow between networked computers. Java has facility to work directly with sockets. Java has facility to work directly with 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 sockets in operation, distinguished by its port number. This allows each host to have a number of sockets in operation, distinguished by its port number.

One called server and the other called client. One called server and the other called client. Client requests data and the server supplies it. Client requests data and the server supplies it.

ServerSockets ServerSocket class is used to create a server application that listens on a specified port for a client requesting service. ServerSocket class is used to create a server application that listens on a specified port for a client requesting service. To create a ServerSocket object, you use a constructor that takes port number as an integer argument. To create a ServerSocket object, you use a constructor that takes port number as an integer argument. Accept( ) method can be used to obtain socket object for private conversation between the server and the client. Accept( ) method can be used to obtain socket object for private conversation between the server and the client.

Methods: T accept( ). Void close( ). Void close( ). InetAddress getInetAddress( ) - get the IP address of the client. InetAddress getInetAddress( ) - get the IP address of the client. int getLocalPort( ) - return the local port on which the ServerSocket is listening. int getLocalPort( ) - return the local port on which the ServerSocket is listening.

InetAddress Class Every machine connected to internet has a unique address, called IP address. Every machine connected to internet has a unique address, called IP address. InetAddress object is retrieved by use of the ServerSocket class’s getInetAddress( ) method. InetAddress object is retrieved by use of the ServerSocket class’s getInetAddress( ) method. InetAddress class provides several class methods that allow you to retrieve an InetAddress object. InetAddress class provides several class methods that allow you to retrieve an InetAddress object.

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 Class The Socket class is used by the server and the client to converse. The Socket class is used by the server and the client to converse. The Socket object is returned by the accept() method of the ServerSocket class. The Socket object is returned by the accept() method of the ServerSocket class. Constructors can also be used to create the Socket class. Constructors can also be used to create the Socket class. Socket(String host, int port). Socket(String host, int port). Socket(InetAddress ipNumber, int port). Socket(InetAddress ipNumber, int port).

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…………...………...

Methods: Methods: String getDirectory( ) String getFile( ) int getMode( ) Void setDirectory(string dir) Void setFile(string file) Void setFilenameFilter(FilenameFilter flt)