SlideShare a Scribd company logo
1 of 28
CHAPTER 5
INPUT OUTPUT AND FILE
OPERATIONS
WHAT IS JAVAAPI???
• API stands for Application Programming Interface.
• It is a collection of communication protocols and subroutines used by
various programs to communicate between them.
• It plays a very important role while building software.
• An API helps two programs or applications to communicate with each
other by providing them with the necessary tools and functions.
• It takes the request from the user and sends it to the service provider
and then again sends the result generated from the service provider to
the desired user.
WHAT IS JAVAAPI???
• An API is similar to a GUI(Graphical User Interface) with one major
difference. Unlike GUIs, an API helps software developers to access
web tools while a GUI helps to make a program easier to understand
by users.
• The working of an API can be clearly explained with a few simple
steps. Think of a client-server architecture where the client sends the
request via a medium to the server and receives the response through
the same medium.
• An API acts as a communication medium between two programs or
systems for functioning.
JAVA IO API
• Java IO API helps the users to read and write data. In simple words,
we can say that the Java IO helps the users to take the input and
produce output based on that input.
• Java I/O (Input and Output) is used to process the input and produce
the output. Java uses the concept of a stream to make I/O operations
fast. The java.io package contains all the classes required for input and
output operations. We can perform file handling in Java by Java I/O
API.
• The Java IO API is placed in the java.io package. This package
comprises almost all classes that a user requires to perform input and
output (I/O) in Java. The java.io package generally involves reading
basic information from a source and writing it to a destination.
JAVA.IO PACKAGE
• The “java.io” package offers classes to read and write files, streams,
and other input/output devices. This package includes classes like
“InputStream,” “OutputStream,” “Reader,” and “Writer.”
• Java performs IO through Stream class.
• Some of the important classes in java.io package are as follows:
BufferedInputStream, BufferedOutputStream, BufferedReader,
BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream,
FileIputStream, FileOutputStream, StringReader, StringWriter, etc.
STREAM CLASS
• A stream can be defined as a sequence of data.
• All these streams represent an input source and an output destination.
• The stream in the java.io package supports many data such as
primitives, object, localized characters, etc.
• The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination. InputStream
and OutputStream are the basic stream classes in Java.
• There are two types of stream classes:
Byte Stream Class
Character Stream Class
BYTE STREAM CLASS
• Byte Stream Classes are used to read bytes from an input stream and
write bytes to an output stream.
• There are many classes related to byte streams but the most frequently
used classes are, FileInputStream and FileOutputStream.
• FileInputStream class is used to read bytes from a file. It should be
used to read byte-oriented data for example to read image, audio,
video etc.
• FileOutputStream is an output stream for writing data to a file.
FileOutputStream will create the file before opening it for output. On
opening a read only file, it will throw an exception.
FileOutputStream Method
Method Meaning
Void write(byte[] b) This method writes b. length bytes from the
specified byte array to this file output stream
Void write(byte[] b, int off, int len) This method writes len bytes from the specified
byte array starting at offset off to this file output
stream
Void write(int b) This method writes the specified byte to this file
output stream
Void close() This method closes this file output stream and
releases any system resources associated with this
stream
FileInputStream Method
Method Meaning
Int available() an estimate of the number of remaining bytes that
can be read
Int read() It is used to read the byte of data from the input
stream
Int read(byte[] b) used to read up to b.length bytes of data from the
input stream.
Int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the
input stream.
Long skip(long x) used to skip over and discards x bytes of data
from the input stream.
Void close() used to closes the stream.
BYTE STREAM CLASS
STREAM CLASS MEANING
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that writes to a file
ByteArrayInputStream Input stream that reads from a byte array
ByteArrayOutputStream Output stream that writes to a byte array
InputStream Abstract class that describes stream input
OutputStream Abstract class that describes stream output
RandomAccessFile Supports random access file I/O
SequenceInputStream Input stream that is a combination of two or more
input streams that will be read sequentially, one
after the other
BufferedInputStream Buffered input stream
BufferedOutputStream Buffered output stream
CHARACTER STREAM CLASS
• Character streams in Java are designed for handling the input and
output of characters. They use 16-bit Unicode characters.
• Though there are many classes related to character streams but the
most frequently used classes are, FileReader and FileWriter.
• Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader
reads two bytes at a time and FileWriter writes two bytes at a time.
CHARACTER STREAM CLASS
STREAM CLASS MEANING
BufferedReader Buffered input character stream
BufferedWriter Buffered output character stream
CharArrayReader Input stream that reads from a character array
CharArrayWriter Output stream that writes to a character array
FileReader Input stream that reads from a file
FileWriter Output stream that writes to a file
InputStreamReader Input stream that translates bytes to characters
OutputStreamWriter Output stream that translates characters to bytes
Reader Abstract class that describes character stream
input
Writer Abstract class that describes character stream
output
SERIALIZATION
• Serialization in Java is a mechanism of writing the state of an object into a
byte-stream, so that it can be stored on to a file, or memory, or a database
for future access. It is mainly used in Hibernate, RMI, JPA, EJB and JMS
technologies.
• The reverse operation of serialization is called deserialization where byte-
stream is converted into an object. The serialization and deserialization
process is platform-independent, it means you can serialize an object on one
platform and deserialize it on a different platform.
• For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
SERIALIZATION
• Syntax for the writeObject() method:
public final void writeObject(Object o) throws IO Exception
• Syntax for the readObject() method:
public final Object readObject() throws IOException,
ClassNotFoundException
NETWORKING
• Sockets are at the foundation of modern networking because a socket
allows a single computer to serve many different clients at once, as
well as to serve many different types of information. This is
accomplished through the use of a port, which is a numbered socket on
a particular machine.
• A server process is said to “listen” to a port until a client connects to it.
A server is allowed to accept multiple clients connected to the same
port number, although each session is unique. To manage multiple
client connections, a server process must be multi threaded or have
some other means of multiplexing the simultaneous I/O.
NETWORKING
• Socket communication takes place via a protocol. Internet Protocol
(IP)is a low-level routing protocol that breaks data into small packets
and sends them to an address across a network, which does not
guarantee to deliver said packets to the destination.
• Transmission Control Protocol(TCP) is a higher-level protocol that
manages to robustly string together these packets, sorting and
retransmitting them as necessary to reliably transmit data.
• A third protocol, User Datagram Protocol (UDP), sits next to TCP and
can be used directly to support fast, connectionless, unreliable
transport of packets.
NETWORKING
• A key component of the Internet is the address. Every computer on the
Internet has one.
• An Internet address is a number that uniquely identifies each computer
on the Net.
• Originally, all Internet addresses consisted of 32-bit values, organized
as four 8-bit values. This address type was specified by IPv4 (Internet
Protocol, version 4).
• However, a new addressing scheme, called IPv6 (Internet Protocol,
version 6) has come into play. IPv6 uses a 128-bit value to represent
an address, organized into eight 16-bit chunks.
DOMAIN NAME SERVER
• Just as the four numbers of an IP address describe a network hierarchy
from left to right, the name of an Internet address, called its domain
name, describes a machine's location in a name space from right to
left.
• For example, www.yahoo.com is in the com domain (commercial
sites), it is called Yahoo (company name) and www is the name of the
specific computer. www corresponds to rightmost number in the
equivalent IP address.
PROXY SERVER
• A proxy server speaks the client side of a protocol to another server.
• This is often required when clients have certain restrictions on which
servers they can connect to.
• Thus a client would connect to a proxy server which did not have such
restrictions and the proxy server would in turn communicate for the
client.
CLIENT SERVER MODEL
• A client is an entity that relies on another entity to accomplish some
task. A server is an entity whose sole purpose is to serve clients by
providing them with some kind of well-defined services such as
searching a database or accepting mail messages.
• The interaction between client and server is just like the interaction
between a lamp and an electrical socket. The power grid of the house
is the server and the lamp is the power client.
• The server is a permanently available resource whereas the client is
free to unplug after it has been served.
NETWORKING CLASSES
• The classes contained in the java.net package are shown below:
• Authenticator, Inet6Address, ServerSocket, CacheRequest,
InetAddress, Socket, CacheResponse, InetSocketAddress,
SocketAddress, ContentHandler, SocketImpel, CookieHandler,
JarURLConnection, SocketPermission, CookieManager,
MulticastSocket, DatagramPacket, NetPermission, DatagramSocket,
NetworkInterface, PasswordAuthentication, URLCLassLoader,
URLConnection, etc.
InetAddress Class
• The InetAddress class is used to convert the Domain Name (or textual
Internet address) of an Internet address into an object which represents
the address.
• The InetAddress class doesn't have any constructors but it has three
factory methods that can be used to create instances of the InetAddress
class.
• Factory methods are merely a convention whereby static methods in a
class return an instance of that class.
InetAddress Class
• Three commonly used InetAddress factory methods are shown here:
• static InetAddress getLocalHost( ) throws UnknownHostException
• static InetAddress getByName(String hostName) throws
UnknownHostException
• static InetAddress[ ] getAllByName(String hostName) throws
UnknownHostException
• InetAddress also includes the factory method getByAddress( ), which
takes an IP address and returns an InetAddress object.
TCP/IP SOCKETS
• TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to
point, stream based between two hosts on the Internet.
• A socket can be used to connect Java's Input/Output system to other programs that
may reside either on the local machine or any other machine on the Internet.
• In Java, TCP sockets are classified as: TCP Server Socket TCP Client Socket
• The java.net package provides two classes that allow you to create the two kinds
of sockets. The classes are Socket and ServerSocket respectively.
• The Socket class, basically used to create client sockets, is designed to connect to
server sockets and initiate protocol exchanges.
• The ServerSocket class, basically used to create server sockets, is designed to be a
listener, which waits for clients to connect before doing anything.
• When you create a Socket object, it implicitly establishes the connection between
the client and the server.
TCP/IP SOCKETS
• The socket class provides some constructors to create client sockets.
Constructor Name Description
Socket(string hostname, int port)
throws UnknownHostException,
IOException
This constructor is used to create a
client socket and connect the local
host to the specified hostName and
port. It can throw an
UnknownHostException or an
IOException.
Socket (InetAddress ipAddress, int
port) throws IOException
This constructor is used to create a
client socket using a pre existing
InetAddress object and a port. It can
throw an IOException.
TCP/IP SOCKETS
• After you have created a socket, you can get the address and port
details associated with the socket by the use of the following methods:
Method Name Description
InetAddress getInetAddress() Returns the address associated with
the socket instance.
Int getPort() Returns the remote port to which this
socket is connected.
Int getLocalPort() Returns the local port to which this
socket instance is connected.
WRITING SERVER PROGRAM USING TCP
Step-1: Create the server socket and begin listening.
Step-2: Call the accept( ) method to get new connections.
Step-3: Create input and output streams for the returned socket.
Step-4: Conduct the conversation based on the agreed protocol.
Step-5: Close the Client Stream and the Socket
Step-6: Go back to step 2 or continue to step 7
Step-7: Close the Server Socket.
WRITING CLIENT PROGRAM USING TCP
• Step-1: Create the client socket connection.
• Step-2: Acquire read and write streams for the socket.
• Step-3: Use the streams according to the server’s protocol.
• Step-4: Close the stream.
• Step-5: Close the socket

More Related Content

Similar to Java IO API and Networking Fundamentals

Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47myrajendra
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesSakkaravarthiS1
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Outputraksharao
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptxRathanMB
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Java programming Chapter 4.pptx
Java programming Chapter 4.pptxJava programming Chapter 4.pptx
Java programming Chapter 4.pptxssusera0d3d2
 

Similar to Java IO API and Networking Fundamentals (20)

IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Basic IO
Basic IOBasic IO
Basic IO
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Various io stream classes .47
Various io stream classes .47Various io stream classes .47
Various io stream classes .47
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
 
Input & output
Input & outputInput & output
Input & output
 
Computer science input and output BASICS.pptx
Computer science input and output BASICS.pptxComputer science input and output BASICS.pptx
Computer science input and output BASICS.pptx
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Chapter 2.1 : Data Stream
Chapter 2.1 : Data StreamChapter 2.1 : Data Stream
Chapter 2.1 : Data Stream
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java programming Chapter 4.pptx
Java programming Chapter 4.pptxJava programming Chapter 4.pptx
Java programming Chapter 4.pptx
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 

Recently uploaded

FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewingbigorange77
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts servicevipmodelshub1
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 

Recently uploaded (20)

FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewing
 
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 

Java IO API and Networking Fundamentals

  • 1. CHAPTER 5 INPUT OUTPUT AND FILE OPERATIONS
  • 2. WHAT IS JAVAAPI??? • API stands for Application Programming Interface. • It is a collection of communication protocols and subroutines used by various programs to communicate between them. • It plays a very important role while building software. • An API helps two programs or applications to communicate with each other by providing them with the necessary tools and functions. • It takes the request from the user and sends it to the service provider and then again sends the result generated from the service provider to the desired user.
  • 3. WHAT IS JAVAAPI??? • An API is similar to a GUI(Graphical User Interface) with one major difference. Unlike GUIs, an API helps software developers to access web tools while a GUI helps to make a program easier to understand by users. • The working of an API can be clearly explained with a few simple steps. Think of a client-server architecture where the client sends the request via a medium to the server and receives the response through the same medium. • An API acts as a communication medium between two programs or systems for functioning.
  • 4. JAVA IO API • Java IO API helps the users to read and write data. In simple words, we can say that the Java IO helps the users to take the input and produce output based on that input. • Java I/O (Input and Output) is used to process the input and produce the output. Java uses the concept of a stream to make I/O operations fast. The java.io package contains all the classes required for input and output operations. We can perform file handling in Java by Java I/O API. • The Java IO API is placed in the java.io package. This package comprises almost all classes that a user requires to perform input and output (I/O) in Java. The java.io package generally involves reading basic information from a source and writing it to a destination.
  • 5. JAVA.IO PACKAGE • The “java.io” package offers classes to read and write files, streams, and other input/output devices. This package includes classes like “InputStream,” “OutputStream,” “Reader,” and “Writer.” • Java performs IO through Stream class. • Some of the important classes in java.io package are as follows: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter, ByteArrayInputStream, ByteArrayOutputStream, FileIputStream, FileOutputStream, StringReader, StringWriter, etc.
  • 6. STREAM CLASS • A stream can be defined as a sequence of data. • All these streams represent an input source and an output destination. • The stream in the java.io package supports many data such as primitives, object, localized characters, etc. • The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the basic stream classes in Java. • There are two types of stream classes: Byte Stream Class Character Stream Class
  • 7. BYTE STREAM CLASS • Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream. • There are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. • FileInputStream class is used to read bytes from a file. It should be used to read byte-oriented data for example to read image, audio, video etc. • FileOutputStream is an output stream for writing data to a file. FileOutputStream will create the file before opening it for output. On opening a read only file, it will throw an exception.
  • 8. FileOutputStream Method Method Meaning Void write(byte[] b) This method writes b. length bytes from the specified byte array to this file output stream Void write(byte[] b, int off, int len) This method writes len bytes from the specified byte array starting at offset off to this file output stream Void write(int b) This method writes the specified byte to this file output stream Void close() This method closes this file output stream and releases any system resources associated with this stream
  • 9. FileInputStream Method Method Meaning Int available() an estimate of the number of remaining bytes that can be read Int read() It is used to read the byte of data from the input stream Int read(byte[] b) used to read up to b.length bytes of data from the input stream. Int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream. Long skip(long x) used to skip over and discards x bytes of data from the input stream. Void close() used to closes the stream.
  • 10. BYTE STREAM CLASS STREAM CLASS MEANING FileInputStream Input stream that reads from a file FileOutputStream Output stream that writes to a file ByteArrayInputStream Input stream that reads from a byte array ByteArrayOutputStream Output stream that writes to a byte array InputStream Abstract class that describes stream input OutputStream Abstract class that describes stream output RandomAccessFile Supports random access file I/O SequenceInputStream Input stream that is a combination of two or more input streams that will be read sequentially, one after the other BufferedInputStream Buffered input stream BufferedOutputStream Buffered output stream
  • 11. CHARACTER STREAM CLASS • Character streams in Java are designed for handling the input and output of characters. They use 16-bit Unicode characters. • Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. • Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
  • 12. CHARACTER STREAM CLASS STREAM CLASS MEANING BufferedReader Buffered input character stream BufferedWriter Buffered output character stream CharArrayReader Input stream that reads from a character array CharArrayWriter Output stream that writes to a character array FileReader Input stream that reads from a file FileWriter Output stream that writes to a file InputStreamReader Input stream that translates bytes to characters OutputStreamWriter Output stream that translates characters to bytes Reader Abstract class that describes character stream input Writer Abstract class that describes character stream output
  • 13. SERIALIZATION • Serialization in Java is a mechanism of writing the state of an object into a byte-stream, so that it can be stored on to a file, or memory, or a database for future access. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. • The reverse operation of serialization is called deserialization where byte- stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform. • For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.
  • 14. SERIALIZATION • Syntax for the writeObject() method: public final void writeObject(Object o) throws IO Exception • Syntax for the readObject() method: public final Object readObject() throws IOException, ClassNotFoundException
  • 15. NETWORKING • Sockets are at the foundation of modern networking because a socket allows a single computer to serve many different clients at once, as well as to serve many different types of information. This is accomplished through the use of a port, which is a numbered socket on a particular machine. • A server process is said to “listen” to a port until a client connects to it. A server is allowed to accept multiple clients connected to the same port number, although each session is unique. To manage multiple client connections, a server process must be multi threaded or have some other means of multiplexing the simultaneous I/O.
  • 16. NETWORKING • Socket communication takes place via a protocol. Internet Protocol (IP)is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. • Transmission Control Protocol(TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit data. • A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets.
  • 17. NETWORKING • A key component of the Internet is the address. Every computer on the Internet has one. • An Internet address is a number that uniquely identifies each computer on the Net. • Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit values. This address type was specified by IPv4 (Internet Protocol, version 4). • However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address, organized into eight 16-bit chunks.
  • 18. DOMAIN NAME SERVER • Just as the four numbers of an IP address describe a network hierarchy from left to right, the name of an Internet address, called its domain name, describes a machine's location in a name space from right to left. • For example, www.yahoo.com is in the com domain (commercial sites), it is called Yahoo (company name) and www is the name of the specific computer. www corresponds to rightmost number in the equivalent IP address.
  • 19. PROXY SERVER • A proxy server speaks the client side of a protocol to another server. • This is often required when clients have certain restrictions on which servers they can connect to. • Thus a client would connect to a proxy server which did not have such restrictions and the proxy server would in turn communicate for the client.
  • 20. CLIENT SERVER MODEL • A client is an entity that relies on another entity to accomplish some task. A server is an entity whose sole purpose is to serve clients by providing them with some kind of well-defined services such as searching a database or accepting mail messages. • The interaction between client and server is just like the interaction between a lamp and an electrical socket. The power grid of the house is the server and the lamp is the power client. • The server is a permanently available resource whereas the client is free to unplug after it has been served.
  • 21. NETWORKING CLASSES • The classes contained in the java.net package are shown below: • Authenticator, Inet6Address, ServerSocket, CacheRequest, InetAddress, Socket, CacheResponse, InetSocketAddress, SocketAddress, ContentHandler, SocketImpel, CookieHandler, JarURLConnection, SocketPermission, CookieManager, MulticastSocket, DatagramPacket, NetPermission, DatagramSocket, NetworkInterface, PasswordAuthentication, URLCLassLoader, URLConnection, etc.
  • 22. InetAddress Class • The InetAddress class is used to convert the Domain Name (or textual Internet address) of an Internet address into an object which represents the address. • The InetAddress class doesn't have any constructors but it has three factory methods that can be used to create instances of the InetAddress class. • Factory methods are merely a convention whereby static methods in a class return an instance of that class.
  • 23. InetAddress Class • Three commonly used InetAddress factory methods are shown here: • static InetAddress getLocalHost( ) throws UnknownHostException • static InetAddress getByName(String hostName) throws UnknownHostException • static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException • InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an InetAddress object.
  • 24. TCP/IP SOCKETS • TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to point, stream based between two hosts on the Internet. • A socket can be used to connect Java's Input/Output system to other programs that may reside either on the local machine or any other machine on the Internet. • In Java, TCP sockets are classified as: TCP Server Socket TCP Client Socket • The java.net package provides two classes that allow you to create the two kinds of sockets. The classes are Socket and ServerSocket respectively. • The Socket class, basically used to create client sockets, is designed to connect to server sockets and initiate protocol exchanges. • The ServerSocket class, basically used to create server sockets, is designed to be a listener, which waits for clients to connect before doing anything. • When you create a Socket object, it implicitly establishes the connection between the client and the server.
  • 25. TCP/IP SOCKETS • The socket class provides some constructors to create client sockets. Constructor Name Description Socket(string hostname, int port) throws UnknownHostException, IOException This constructor is used to create a client socket and connect the local host to the specified hostName and port. It can throw an UnknownHostException or an IOException. Socket (InetAddress ipAddress, int port) throws IOException This constructor is used to create a client socket using a pre existing InetAddress object and a port. It can throw an IOException.
  • 26. TCP/IP SOCKETS • After you have created a socket, you can get the address and port details associated with the socket by the use of the following methods: Method Name Description InetAddress getInetAddress() Returns the address associated with the socket instance. Int getPort() Returns the remote port to which this socket is connected. Int getLocalPort() Returns the local port to which this socket instance is connected.
  • 27. WRITING SERVER PROGRAM USING TCP Step-1: Create the server socket and begin listening. Step-2: Call the accept( ) method to get new connections. Step-3: Create input and output streams for the returned socket. Step-4: Conduct the conversation based on the agreed protocol. Step-5: Close the Client Stream and the Socket Step-6: Go back to step 2 or continue to step 7 Step-7: Close the Server Socket.
  • 28. WRITING CLIENT PROGRAM USING TCP • Step-1: Create the client socket connection. • Step-2: Acquire read and write streams for the socket. • Step-3: Use the streams according to the server’s protocol. • Step-4: Close the stream. • Step-5: Close the socket

Editor's Notes

  1. Let’s take a real-life example of an API, you can think of an API like a waiter in a restaurant who listens to your order request, goes to the chef, takes the food items ordered and gets back to you with the order. Also, if you want to look for the working of an API with the example, here’s one. You’re searching for a course on the XYZ website, you send a request through an API, and the database searches for the course and checks if it’s available, the API is responsible here to send your request to the database and responds with the output.
  2. A developer extensively uses APIs in his software to implement various features by using an API call without writing complex codes for the same. We can create an API for an operating system, database system, hardware system, JavaScript file, or similar object-oriented files.
  3. It provides a convenient means for handling input and output of byte.
  4. b - the buffer into which the data is read. off - the start offset in the destination array b len - the maximum number of bytes read.
  5. Character Streams provide a convenient means for handling input and output of characters. Internationalization is possible as it uses Unicode. For character streams we have two base classes Reader Writer
  6. If you want a class object to be serializable, all you need to do it implement the java.io.Serializable interface.
  7. When two or more computers want to communicate with each other to share data or resources then the communications among them can be done through networking.
  8. According to Object Oriented Program, the term factory applies to a class that can construct instances of that class without invoking constructors. The instance of the class are constructed through static methods built into the class.
  9. The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to resolve the host name, they throw an UnknownHostException. The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It will also throw an UnknownHostException if it can’t resolve the name to at least one address.
  10. Since TCP is a stream based protocol, every TCP socket is associated with input and output streams.