SlideShare une entreprise Scribd logo
1  sur  67
Télécharger pour lire hors ligne
Programming in Java
I/O Basics and Streams
By
Ravi Kant Sahu
Asst. Professor

Lovely Professional University, Punjab
Introduction
• Most real applications of Java are not text-based, console
programs.
• Java’s support for console I/O is limited.
• Text-based console I/O is not very important to Java
programming.
• Java does provide strong, flexible support for I/O as it relates to
files and networks.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Streams
• Java implements streams within class hierarchies defined in the
java.io package.
• A stream is an ordered sequence of data.
• A stream is linked to a physical device by the Java I/O system.
• All streams behave in the same manner, even if the actual
physical devices to which they are linked differ.
• An I/O Stream represents an input source or an output
destination.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
I/O Streams
• A stream can represent many different kinds of sources and
destinations
– disk files, devices, other programs, a network socket, and
memory arrays
• Streams support many different kinds of data
– simple bytes, primitive data types, localized characters, and
objects
• Some streams simply pass on data; others manipulate and
transform the data in useful ways.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Input Stream
• A program uses an input stream to read data from a source, one
item at a time.

Reading information into a program.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Output Stream
• A program uses an output stream to write data to a destination,
one item at time:

Writing information from a program.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Types of Streams
• Java defines two different types of Streams Byte Streams
 Character Streams
• Byte streams provide a convenient means for handling input and
output of bytes.
• Byte streams are used, for example, when reading or writing
binary data.
• Character streams provide a convenient means for handling
input and output of characters.
• In some cases, character streams are more efficient than byte
streams.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Byte Streams
• Programs use byte streams to perform input and output of 8-bit bytes.
• Byte streams are defined by using two class hierarchies.
• At the top, there are two abstract classes: InputStream and
OutputStream.
• The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement.
• Two of the most important methods are read( )and write( ), which,
respectively, read and write bytes of data.
• Both methods are declared as abstract inside InputStream and
OutputStream.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Reading/ Writing File using Streams

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using Byte Streams
import java.io.*;
public class CopyBytes {
public static void main(String[] args) throws IOException
{ FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(“ravi.txt");
out = new FileOutputStream(“Copy.txt");
int c;
while ((c = in.read()) != -1)
{ out.write(c); }
}
finally { if (in != null)
{ in.close(); }
if (out != null)
{ out.close(); }
}}}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Byte Stream Contd…
Note: read() returns an int value.
• If the input is a stream of bytes, why doesn't read() return
a byte value?
• Using a int as a return type allows read() to use -1 to indicate
that it has reached the end of the stream.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Closing the Streams
• Closing a stream when it's no longer needed is very important.
• It is so important that we have used a finally block to guarantee that
both streams will be closed even if an error occurs. This practice
helps avoid serious resource leaks.
• That's why CopyBytes makes sure that each stream variable contains
an object reference before invoking close.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Use of Byte Stream
• Byte streams should only be used for the most primitive I/O.
• Since ravi.txt contains character data, the best approach is to
use character streams.
• Byte Stream represents a kind of low-level I/O.
• So why talk about byte streams?
• Because all other stream types are built on byte streams.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Byte Stream Classes
Stream Class

Meaning / Use

BufferedInputStream

Buffered input stream

BufferedOutputStream

Buffered output stream

DataInputStream

contains methods for reading the Java standard
data types

DataOutputStream

contains methods for writing the Java standard
data types

FileInputStream

Input stream that reads from a file

FileOutputStream

Output stream that writes to a file

InputStream

Abstract class that describes stream input

OutputStream

Abstract class that describes stream output

PrintStream

Output stream that contains print() and println(
)

PipedInputStream
PipedOutputStream

Input Pipe
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Output Pipe
Methods defined by ‘InputStream’

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods defined by ‘OutputStream’

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Character Stream
• The Java platform stores character values using Unicode conventions.
• Character stream I/O automatically translates this internal format to
and from the local character set.
• Character streams are defined by using two class hierarchies.
• At the top are two abstract classes, Reader and Writer.
• These abstract classes handle Unicode character streams.
• Similar to Byte Streams, read() and write() methods are defined in
Reader and Writer class.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Character Stream Classes

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods defined by ‘Reader’

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods defined by ‘Writer’

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Predefined Streams
• java.lang package defines a class called System, which
encapsulates several aspects of the run-time environment.
• System contains three predefined stream variables:
in, out, and err.
• These fields are declared as public, static, and final within
System.
• This means that they can be used by any other part of your
program and without reference to a specific System object.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Predefined Streams
• System.out refers to the standard output stream. By default, this is the
console.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the
console by default.
• However, these streams may be redirected to any compatible I/O
device.
• System.in is an object of type InputStream;
• System.out and System.err are objects of type PrintStream.
• These are byte streams, even though they typically are used to read
and write characters from and to the console.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Reading Console Input
•
•

In Java 1.0, the only way to perform console input was to use a byte stream.
In Java, console input is accomplished by reading from System.in.

•

To obtain a character-based stream that is attached to the console, wrap
System.in in a BufferedReader object.

•
•

BufferedReader supports a buffered input stream.
Its most commonly used constructor is:
BufferedReader (Reader inputReader)

•

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

•

Reader is an abstract class. One of its concrete subclasses is
InputStreamReader, which converts bytes to characters.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• To obtain an InputStreamReader object that is linked to System.in,
use the following constructor:
InputStreamReader(InputStream inputStream)
• Because System.in refers to an object of type InputStream, it can be
used for inputStream.
• Putting it all together, the following line of code creates a
BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
• After this statement executes, br is a character-based stream that is
linked to the console through System.in.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
reading Characters and Strings
• To read a character from a BufferedReader, use read( ).
int read( ) throws IOException
• Each time read( ) is called, it reads a character from the input stream
and returns it as an integer value.
• It returns –1 when the end of the stream is encountered.
• It can throw an IOException.
• To read a string from the keyboard, use readLine( ) that is a member
of the BufferedReader class.
String readLine( ) throws IOException

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
reading Characters
• To read a character from a BufferedReader, use read( ).
int read( ) throws IOException
• Each time read( ) is called, it reads a character from the input
stream and returns it as an integer value.
• It returns –1 when the end of the stream is encountered.
• It can throw an IOException.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
reading Characters
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
}
while(c != 'q');
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
reading String
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
}
while(!str.equals("stop"));
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Writing Console Output
• print() and println(), defined by PrintStream class, are used.
• System.out is a ByteStream for referencing these methods.
• PrintStream is an output stream derived from OutputStream, it
also implements write( ) which can be used to write to the
console.
void write(int byte_val)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class WriteDemo
{
public static void main(String args[])
{
int b;
b = 'A';
System.out.write(b);
System.out.write('n');
}
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
PrinterWriter Class
• Although using System.out to write to the console is acceptable.
• The recommended method of writing to the console when using
Java is through a PrintWriter stream.
• PrintWriter is one of the character-based classes.
• Using a character-based class for console output makes it easier to
internationalize your program.
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• outputStream is an object of type OutputStream.
• flushOnNewline controls whether Java flushes the output stream
every time a println( )method is called.
• If flushOnNewline is true, flushing automatically takes place.
• If false, flushing is not automatic.
• PrintWriter supports the print( ) and println( ) methods for all types
including Object. Thus, we can use these methods in the same way
as they have been used with System.out.
• If an argument is not a simple type, the PrintWriter methods call the
object’s toString( ) method and then print the result.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Using PrintWriter
import java.io.*;
public class PrintWriterDemo
{
public static void main(String args[])
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println(“Using PrintWriter Object");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Files
File Class
• The File class provides the methods for obtaining the properties
of a file/directory and for renaming and deleting a file/directory.
• An absolute file name (or full name) contains a file name with
its complete path and drive letter.
• For example, c:bookWelcome.java
• A relative file name is in relation to the current working
directory.
• The complete directory path for a relative file name is omitted.
• For example, Welcome.java

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
File Class
• The File class is a wrapper class for the file name and its
directory path.
• For example, new File("c:book") creates a File object for the
directory c:book,
• and new File("c:booktest.dat") creates a File object for the
file c:booktest.dat, both on Windows.
• File class does not contain the methods for reading and writing
file contents.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods and Constructors
Constructor:

File(String path_name)
• Creates a File object for the specified path name. The path name
may be a directory or a file.
Methods:
boolean isFile()
boolean isDirectory()
boolean exists()
boolean canRead()
boolean canWrite()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods and Constructors
String getName()
String getPath()
String getAbsolutePath()
long lastModified()
long length()
boolean delete()
boolean renameTo(String name)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Reading and Writing Files
• In Java, all files are byte-oriented, and Java provides methods to
read and write bytes from and to a file.
• Java allows us to wrap a byte-oriented file stream within a
character-based object.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Binary i/O classes
Binary Input/Output Classes

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
FileInputStream and FileOutputStream
• FileInputStream and FileOutputStream are stream classes which
create byte streams linked to files.
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
• When an output file is opened, any pre-existing file by the same
name is destroyed.
• Files must be closed using close(), when you are done.
void close( ) throws IOException
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Reading and Writing Files
• To read from a file, we can use read( ) that is defined with in
FileInputStream.
int read( ) throws IOException
• Each time read() is called, it reads a single byte from the file
and returns the byte as an integer value.
• To write to a file, we can use the write( )method defined by
FileOutputStream.
void write(int byteval) throws IOException

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
import java.io.*;
class CopyFile {
public static void main(String args[])throws IOException{
int i; FileInputStream fin=null; FileOutputStream fout=null;
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
}
while(i != -1);
}
catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
FilterInputStream & FilterOutputStream
• The basic byte input stream provides a read() method that can be used
only for reading bytes.
• If we want to read integers, doubles, or strings, we need a filter class to
wrap the byte input stream.
• Filter class enables us to read integers, doubles, and strings instead of
bytes and characters.
• FilterInputStream and FilterOutputStream are the base classes for
filtering data.
• When we need to process primitive numeric types, we use
DataInputStream and DataOutputStream to filter bytes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DataInputStream & DataOutputStream
• DataInputStream reads bytes from the stream and converts them
into appropriate primitive type values or strings.
• DataOutputStream converts primitive type values or strings into
bytes and outputs the bytes to the stream.
• DataInputStream/DataOutputStream extends FilterInputStream/
FilterOutputStream and implements DataInput/DataOutput
interface respectively.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor and Methods of DataInputStream

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor and Methods of DataOutputStream

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
BufferedInputStream/ BufferedOutputStream
• Used to speed up input and output by reducing the number of disk
reads and writes.
• Using BufferedInputStream, the whole block of data on the disk
is read into the buffer in the memory once.
• The individual data are is delivered to the program from the
buffer.
• Using BufferedOutputStream, the individual data are first written
to the buffer in the memory.
• When the buffer is full, all data in the buffer is written to the disk.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructors of
BufferedInputStream and BufferedOutputSTream
• BufferedInputStream (InputStream in)
• BufferedInputStream(InputStream in, int bufferSize)

• BufferedOutputStream (OutputStream in)
• BufferedOutputStream(OutputStream in, int bufferSize)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of
BufferedInputStream and BufferedOutputSTream
• BufferedInputStream/BufferedOutputStream does not contain new
methods.
• All the methods are inherited from the InputStream/OutputStream
classes.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Object Input/Output
• ObjectInputStream/ObjectOutputStream classes can be used to
read/write serializable objects.
• ObjectInputStream/ObjectOutputStream enables you to perform
I/O for objects in addition to primitive type values and strings.
• ObjectInputStream/ObjectOutputStream contains all the functions
of DataInputStream/ DataOutputStream.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor and Methods of ObjectInputStream

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor and Methods of ObjectOutputStream

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Serialization

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Serialization
• Serialization is the process of writing the state of an object to a
byte stream.
• This is useful when we want to save the state of our program to a
persistent storage area, such as a file.
• At a later time, we may restore these objects by using the process
of de-serialization.
• Serialization is also needed to implement Remote Method
Invocation (RMI).

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• An object to be serialized may have references to other objects,
which, in turn, have references to still more objects.
• If we attempt to serialize an object at the top of an object graph,
all of the other referenced objects are recursively located and
serialized.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Serialization: Interfaces and Classes
• An overview of the interfaces and classes that support
serialization follows:
1) Serializable
– Only an object that implements the Serializable interface can
be saved and restored by the serialization facilities.
– The Serializable interface defines no members.
– It is simply used to indicate that a class may be serialized.
– If a class is serializable, all of its subclasses are also
serializable.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
2) Externalizable
•
•

The Externalizable interface is designed for compression or
encryption .
The Externalizable interface defines two methods:
void readExternal (ObjectInput inStream)throws IOException,
ClassNotFoundException
void writeExternal (ObjectOutput outStream) throws IOException

•

In these methods, inStream is the byte stream from which the object
is to be read, and outStream is the byte stream to which the object is
to be written.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Serialization Example
class MyClass implements Serializable
{
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString()
{
return "s=" + s + "; i=" + i + "; d=" + d;
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
import java.io.*;
public class SerializationDemo {
public static void main(String args[]) {
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Random access File

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Random Access File
• RandomAccessFile class to allow a file to be read from and
written to at random locations.
• It implements the interfaces DataInput and DataOutput, which
define the basic I/O methods.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• RandomAccessFile is special because it supports positioning
requests within the file.
RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
RandomAccessFile(String filename, String access)
throws FileNotFoundException
• “r”, then the file can be read, but not written
• “rw”,then the file is opened in read-write mode

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods
• The method seek() is used to set the current position of the file
pointer within the file:
void seek(long newPos) throws IOException
• Here, newPos specifies the new position of the file pointer
from the beginning of the file.
• After a call to seek( ), the next read or write operation will
occur at the new file position.

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods
• length() returns the length of the file.
long length()
• getFilePointer() returns the offset, in bytes, from the beginning
of the file to where the next read or write occurs.
long getFilePointer()
• setLength() is used to setsa new length for file.
void setLength(long newLength)

Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Contenu connexe

Tendances

Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Fresherszynofustechnology
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and InterfaceHaris Bin Zahid
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1İbrahim Kürce
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programmingAmar Jukuntla
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Objectdkpawar
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Sakthi Durai
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and VariablesNilesh Dalvi
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSkillwise Group
 
SQL Interview Questions For Experienced
SQL Interview Questions For ExperiencedSQL Interview Questions For Experienced
SQL Interview Questions For Experiencedzynofustechnology
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm Madishetty Prathibha
 

Tendances (20)

Internationalization
InternationalizationInternationalization
Internationalization
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Packages
PackagesPackages
Packages
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 
Abstract class and Interface
Abstract class and InterfaceAbstract class and Interface
Abstract class and Interface
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programming
 
Networking
NetworkingNetworking
Networking
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
SKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPTSKILLWISE - OOPS CONCEPT
SKILLWISE - OOPS CONCEPT
 
SQL Interview Questions For Experienced
SQL Interview Questions For ExperiencedSQL Interview Questions For Experienced
SQL Interview Questions For Experienced
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
oop Lecture19
oop Lecture19oop Lecture19
oop Lecture19
 

En vedette (10)

Collection framework
Collection frameworkCollection framework
Collection framework
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Jdbc
JdbcJdbc
Jdbc
 
Servlets
ServletsServlets
Servlets
 
Event handling
Event handlingEvent handling
Event handling
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
List classes
List classesList classes
List classes
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 

Similaire à Basic IO

L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxnoonoboom
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxSadhilAggarwal
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Outputraksharao
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptxssuser9d7049
 
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
 
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
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfhemanth248901
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and OutputDucat India
 
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
 

Similaire à Basic IO (20)

L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptxChapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
Chapter 13_m5JAVANOTESAPPLETS,INPUT.pptx
 
CHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptxCHAPTER 5 mechanical engineeringasaaa.pptx
CHAPTER 5 mechanical engineeringasaaa.pptx
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
 
Stream In Java.pptx
Stream In Java.pptxStream In Java.pptx
Stream In Java.pptx
 
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
 
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
 
inputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdfinputoutputstreams-140612032817-phpapp02.pdf
inputoutputstreams-140612032817-phpapp02.pdf
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Java I/O
Java I/OJava I/O
Java I/O
 
Input & output
Input & outputInput & output
Input & output
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Oodp mod4
Oodp mod4Oodp mod4
Oodp mod4
 
Java Input and Output
Java Input and OutputJava Input and Output
Java Input and Output
 
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
 
Unit IV Notes.docx
Unit IV Notes.docxUnit IV Notes.docx
Unit IV Notes.docx
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 

Plus de Ravi_Kant_Sahu

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaRavi_Kant_Sahu
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi_Kant_Sahu
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 

Plus de Ravi_Kant_Sahu (11)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Packages
PackagesPackages
Packages
 
Array
ArrayArray
Array
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 

Dernier

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Dernier (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Basic IO

  • 1. Programming in Java I/O Basics and Streams By Ravi Kant Sahu Asst. Professor Lovely Professional University, Punjab
  • 2. Introduction • Most real applications of Java are not text-based, console programs. • Java’s support for console I/O is limited. • Text-based console I/O is not very important to Java programming. • Java does provide strong, flexible support for I/O as it relates to files and networks. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Streams • Java implements streams within class hierarchies defined in the java.io package. • A stream is an ordered sequence of data. • A stream is linked to a physical device by the Java I/O system. • All streams behave in the same manner, even if the actual physical devices to which they are linked differ. • An I/O Stream represents an input source or an output destination. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. I/O Streams • A stream can represent many different kinds of sources and destinations – disk files, devices, other programs, a network socket, and memory arrays • Streams support many different kinds of data – simple bytes, primitive data types, localized characters, and objects • Some streams simply pass on data; others manipulate and transform the data in useful ways. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Input Stream • A program uses an input stream to read data from a source, one item at a time. Reading information into a program. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Output Stream • A program uses an output stream to write data to a destination, one item at time: Writing information from a program. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. Types of Streams • Java defines two different types of Streams Byte Streams  Character Streams • Byte streams provide a convenient means for handling input and output of bytes. • Byte streams are used, for example, when reading or writing binary data. • Character streams provide a convenient means for handling input and output of characters. • In some cases, character streams are more efficient than byte streams. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Byte Streams • Programs use byte streams to perform input and output of 8-bit bytes. • Byte streams are defined by using two class hierarchies. • At the top, there are two abstract classes: InputStream and OutputStream. • The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. • Two of the most important methods are read( )and write( ), which, respectively, read and write bytes of data. • Both methods are declared as abstract inside InputStream and OutputStream. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Reading/ Writing File using Streams Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Using Byte Streams import java.io.*; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(“ravi.txt"); out = new FileOutputStream(“Copy.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }}} Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Byte Stream Contd… Note: read() returns an int value. • If the input is a stream of bytes, why doesn't read() return a byte value? • Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Closing the Streams • Closing a stream when it's no longer needed is very important. • It is so important that we have used a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks. • That's why CopyBytes makes sure that each stream variable contains an object reference before invoking close. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Use of Byte Stream • Byte streams should only be used for the most primitive I/O. • Since ravi.txt contains character data, the best approach is to use character streams. • Byte Stream represents a kind of low-level I/O. • So why talk about byte streams? • Because all other stream types are built on byte streams. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Byte Stream Classes Stream Class Meaning / Use BufferedInputStream Buffered input stream BufferedOutputStream Buffered output stream DataInputStream contains methods for reading the Java standard data types DataOutputStream contains methods for writing the Java standard data types FileInputStream Input stream that reads from a file FileOutputStream Output stream that writes to a file InputStream Abstract class that describes stream input OutputStream Abstract class that describes stream output PrintStream Output stream that contains print() and println( ) PipedInputStream PipedOutputStream Input Pipe Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Output Pipe
  • 15. Methods defined by ‘InputStream’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Methods defined by ‘OutputStream’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Character Stream • The Java platform stores character values using Unicode conventions. • Character stream I/O automatically translates this internal format to and from the local character set. • Character streams are defined by using two class hierarchies. • At the top are two abstract classes, Reader and Writer. • These abstract classes handle Unicode character streams. • Similar to Byte Streams, read() and write() methods are defined in Reader and Writer class. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. Character Stream Classes Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Methods defined by ‘Reader’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. Methods defined by ‘Writer’ Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. Predefined Streams • java.lang package defines a class called System, which encapsulates several aspects of the run-time environment. • System contains three predefined stream variables: in, out, and err. • These fields are declared as public, static, and final within System. • This means that they can be used by any other part of your program and without reference to a specific System object. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. Predefined Streams • System.out refers to the standard output stream. By default, this is the console. • System.in refers to standard input, which is the keyboard by default. • System.err refers to the standard error stream, which also is the console by default. • However, these streams may be redirected to any compatible I/O device. • System.in is an object of type InputStream; • System.out and System.err are objects of type PrintStream. • These are byte streams, even though they typically are used to read and write characters from and to the console. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. Reading Console Input • • In Java 1.0, the only way to perform console input was to use a byte stream. In Java, console input is accomplished by reading from System.in. • To obtain a character-based stream that is attached to the console, wrap System.in in a BufferedReader object. • • BufferedReader supports a buffered input stream. Its most commonly used constructor is: BufferedReader (Reader inputReader) • Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. • Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. • To obtain an InputStreamReader object that is linked to System.in, use the following constructor: InputStreamReader(InputStream inputStream) • Because System.in refers to an object of type InputStream, it can be used for inputStream. • Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); • After this statement executes, br is a character-based stream that is linked to the console through System.in. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. reading Characters and Strings • To read a character from a BufferedReader, use read( ). int read( ) throws IOException • Each time read( ) is called, it reads a character from the input stream and returns it as an integer value. • It returns –1 when the end of the stream is encountered. • It can throw an IOException. • To read a string from the keyboard, use readLine( ) that is a member of the BufferedReader class. String readLine( ) throws IOException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. reading Characters • To read a character from a BufferedReader, use read( ). int read( ) throws IOException • Each time read( ) is called, it reads a character from the input stream and returns it as an integer value. • It returns –1 when the end of the stream is encountered. • It can throw an IOException. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. reading Characters import java.io.*; class BRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. reading String import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Writing Console Output • print() and println(), defined by PrintStream class, are used. • System.out is a ByteStream for referencing these methods. • PrintStream is an output stream derived from OutputStream, it also implements write( ) which can be used to write to the console. void write(int byte_val) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('n'); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. PrinterWriter Class • Although using System.out to write to the console is acceptable. • The recommended method of writing to the console when using Java is through a PrintWriter stream. • PrintWriter is one of the character-based classes. • Using a character-based class for console output makes it easier to internationalize your program. PrintWriter(OutputStream outputStream, boolean flushOnNewline) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. • outputStream is an object of type OutputStream. • flushOnNewline controls whether Java flushes the output stream every time a println( )method is called. • If flushOnNewline is true, flushing automatically takes place. • If false, flushing is not automatic. • PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus, we can use these methods in the same way as they have been used with System.out. • If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. Using PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println(“Using PrintWriter Object"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 34. Files
  • 35. File Class • The File class provides the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory. • An absolute file name (or full name) contains a file name with its complete path and drive letter. • For example, c:bookWelcome.java • A relative file name is in relation to the current working directory. • The complete directory path for a relative file name is omitted. • For example, Welcome.java Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. File Class • The File class is a wrapper class for the file name and its directory path. • For example, new File("c:book") creates a File object for the directory c:book, • and new File("c:booktest.dat") creates a File object for the file c:booktest.dat, both on Windows. • File class does not contain the methods for reading and writing file contents. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 37. Methods and Constructors Constructor: File(String path_name) • Creates a File object for the specified path name. The path name may be a directory or a file. Methods: boolean isFile() boolean isDirectory() boolean exists() boolean canRead() boolean canWrite() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. Methods and Constructors String getName() String getPath() String getAbsolutePath() long lastModified() long length() boolean delete() boolean renameTo(String name) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 39. Reading and Writing Files • In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. • Java allows us to wrap a byte-oriented file stream within a character-based object. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 41. Binary Input/Output Classes Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 42. FileInputStream and FileOutputStream • FileInputStream and FileOutputStream are stream classes which create byte streams linked to files. FileInputStream(String fileName) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException • When an output file is opened, any pre-existing file by the same name is destroyed. • Files must be closed using close(), when you are done. void close( ) throws IOException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 43. Reading and Writing Files • To read from a file, we can use read( ) that is defined with in FileInputStream. int read( ) throws IOException • Each time read() is called, it reads a single byte from the file and returns the byte as an integer value. • To write to a file, we can use the write( )method defined by FileOutputStream. void write(int byteval) throws IOException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 44. import java.io.*; class CopyFile { public static void main(String args[])throws IOException{ int i; FileInputStream fin=null; FileOutputStream fout=null; fin = new FileInputStream(args[0]); fout = new FileOutputStream(args[1]); try { do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("File Error"); } fin.close(); fout.close(); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 45. FilterInputStream & FilterOutputStream • The basic byte input stream provides a read() method that can be used only for reading bytes. • If we want to read integers, doubles, or strings, we need a filter class to wrap the byte input stream. • Filter class enables us to read integers, doubles, and strings instead of bytes and characters. • FilterInputStream and FilterOutputStream are the base classes for filtering data. • When we need to process primitive numeric types, we use DataInputStream and DataOutputStream to filter bytes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 46. DataInputStream & DataOutputStream • DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. • DataOutputStream converts primitive type values or strings into bytes and outputs the bytes to the stream. • DataInputStream/DataOutputStream extends FilterInputStream/ FilterOutputStream and implements DataInput/DataOutput interface respectively. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 47. Constructor and Methods of DataInputStream Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 48. Constructor and Methods of DataOutputStream Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 49. BufferedInputStream/ BufferedOutputStream • Used to speed up input and output by reducing the number of disk reads and writes. • Using BufferedInputStream, the whole block of data on the disk is read into the buffer in the memory once. • The individual data are is delivered to the program from the buffer. • Using BufferedOutputStream, the individual data are first written to the buffer in the memory. • When the buffer is full, all data in the buffer is written to the disk. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 50. Constructors of BufferedInputStream and BufferedOutputSTream • BufferedInputStream (InputStream in) • BufferedInputStream(InputStream in, int bufferSize) • BufferedOutputStream (OutputStream in) • BufferedOutputStream(OutputStream in, int bufferSize) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 51. Methods of BufferedInputStream and BufferedOutputSTream • BufferedInputStream/BufferedOutputStream does not contain new methods. • All the methods are inherited from the InputStream/OutputStream classes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 52. Object Input/Output • ObjectInputStream/ObjectOutputStream classes can be used to read/write serializable objects. • ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition to primitive type values and strings. • ObjectInputStream/ObjectOutputStream contains all the functions of DataInputStream/ DataOutputStream. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 53. Constructor and Methods of ObjectInputStream Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 54. Constructor and Methods of ObjectOutputStream Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 55. Serialization Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 56. Serialization • Serialization is the process of writing the state of an object to a byte stream. • This is useful when we want to save the state of our program to a persistent storage area, such as a file. • At a later time, we may restore these objects by using the process of de-serialization. • Serialization is also needed to implement Remote Method Invocation (RMI). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 57. • An object to be serialized may have references to other objects, which, in turn, have references to still more objects. • If we attempt to serialize an object at the top of an object graph, all of the other referenced objects are recursively located and serialized. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 58. Serialization: Interfaces and Classes • An overview of the interfaces and classes that support serialization follows: 1) Serializable – Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. – The Serializable interface defines no members. – It is simply used to indicate that a class may be serialized. – If a class is serializable, all of its subclasses are also serializable. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 59. 2) Externalizable • • The Externalizable interface is designed for compression or encryption . The Externalizable interface defines two methods: void readExternal (ObjectInput inStream)throws IOException, ClassNotFoundException void writeExternal (ObjectOutput outStream) throws IOException • In these methods, inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 60. Serialization Example class MyClass implements Serializable { String s; int i; double d; public MyClass(String s, int i, double d) { this.s = s; this.i = i; this.d = d; } public String toString() { return "s=" + s + "; i=" + i + "; d=" + d; } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 61. import java.io.*; public class SerializationDemo { public static void main(String args[]) { try { MyClass object1 = new MyClass("Hello", -7, 2.7e10); System.out.println("object1: " + object1); FileOutputStream fos = new FileOutputStream("serial"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object1); oos.flush(); oos.close(); } catch(IOException e) { System.out.println("Exception during serialization: " + e); System.exit(0); } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 62. // Object deserialization try { MyClass object2; FileInputStream fis = new FileInputStream("serial"); ObjectInputStream ois = new ObjectInputStream(fis); object2 = (MyClass)ois.readObject(); ois.close(); System.out.println("object2: " + object2); } catch(Exception e) { System.out.println("Exception during deserialization: " + e); System.exit(0); } } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 63. Random access File Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 64. Random Access File • RandomAccessFile class to allow a file to be read from and written to at random locations. • It implements the interfaces DataInput and DataOutput, which define the basic I/O methods. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 65. • RandomAccessFile is special because it supports positioning requests within the file. RandomAccessFile(File fileObj, String access) throws FileNotFoundException RandomAccessFile(String filename, String access) throws FileNotFoundException • “r”, then the file can be read, but not written • “rw”,then the file is opened in read-write mode Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 66. Methods • The method seek() is used to set the current position of the file pointer within the file: void seek(long newPos) throws IOException • Here, newPos specifies the new position of the file pointer from the beginning of the file. • After a call to seek( ), the next read or write operation will occur at the new file position. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 67. Methods • length() returns the length of the file. long length() • getFilePointer() returns the offset, in bytes, from the beginning of the file to where the next read or write occurs. long getFilePointer() • setLength() is used to setsa new length for file. void setLength(long newLength) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)