0% found this document useful (0 votes)
22 views

Stream Based I o

The document discusses Java's stream-based input/output system. It introduces the java.io package, which supports basic I/O through streams. Streams abstract physical devices and behave consistently. Input streams can represent different sources like files or networks. Byte and character streams handle bytes and characters respectively. Standard streams provide console input/output. Common classes for file I/O include FileInputStream and FileOutputStream.

Uploaded by

Vaish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Stream Based I o

The document discusses Java's stream-based input/output system. It introduces the java.io package, which supports basic I/O through streams. Streams abstract physical devices and behave consistently. Input streams can represent different sources like files or networks. Byte and character streams handle bytes and characters respectively. Standard streams provide console input/output. Common classes for file I/O include FileInputStream and FileOutputStream.

Uploaded by

Vaish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Stream Based IO in Java

Rajam Naidu
Stream based I/O (java.io) -1
• This topic introduces one of Java’s most important packages, java.io,
which supports Java’s basic I/O (input/output) system, including file I/O.

• Java programs perform I/O through streams. A stream is an abstraction


that either produces or consumes information. 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.
Stream based I/O (java.io) - 2

• This means that an input stream can abstract many different


kinds of input: from a disk file, a keyboard, or a network socket.

• Likewise, an output stream may refer to the console, a disk file,


or a network connection.

• Java implements streams within class hierarchies defined in


the java.io package.
Stream based I/O (java.io) - 3
• Java defines two types of streams: byte and character.
• 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. They use Unicode and,
therefore, can be internationalized.
• Also, in some cases, character streams are more efficient than
byte streams.
Byte Streams -1

• Byte streams are defined by using two class hierarchies.

• At the top are two abstract classes: InputStream and


OutputStream.

• Each of these abstract classes has several concrete subclasses


that handle the differences among various devices, such as disk
files, network connections, and even memory buffers.
Byte Streams -2

• Java byte streams are used to perform input and output of 8-bit
bytes. Though there are many classes related to byte streams
but the most frequently used classes are , FileInputStream and
FileOutputStream.

• Following is an example which makes use of these two classes


to copy an input file into an output file:
Standard Streams -1

• All the programming languages provide support for standard


I/O where user's program can take input from a keyboard and
then produce output on the computer screen. If you know in C
or C++ programming languages, there were three standard
devices STDIN, STDOUT and STDERR. Similarly Java provides
following three standard streams:
Standard Streams - 2

• Standard Input: This is used to read the data, usually from a


keyboard as standard input stream and represented as System.in.

• Standard Output: This is used to output the data, usually a computer


screen as standard output stream and represented as System.out.

• Standard Error: This is used to output the error, usually a computer


screen as standard error stream and represented as System.err.
Input, Output hierarchy of classes
FileInputStream:
• This stream is used for reading data from the files. Objects can be
created using the keyword new and there are several types of
constructors available.
• Following constructor takes a file name as a string to create an input
stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");
• Following constructor takes a file object to create an input stream
object to read the file. First we create a file object using File()
method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Methods available in File
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
FileInputStream
• 1. public void close() throws IOException{}
This method closes the file output stream. Releases any system resources associated with the file.
Throws an IOException.
• 2. protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file output
stream is called when there are no more references to this stream. Throws an IOException.
• 3. public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an int. Returns the next
byte of data and -1 will be returned if it's the end of the file.
• 4. public int read(byte r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of
bytes read. If it is the end of the file, -1 will be returned.
• 5. public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream. Returns an int.
FileOutputStream
• FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.
• Here are two constructors which can be used to create a FileOutputStream
object.
• Following constructor takes a file name as a string to create an input
stream object to write the file −
• OutputStream f = new FileOutputStream("C:/java/hello")
• Following constructor takes a file object to create an output stream object
to write the file. First, we create a file object using File() method as follows
• File f = new File("C:/java/hello");
• OutputStream f = new FileOutputStream(f);
Console Class -1
• The Java.io.Console class provides methods to access the
character-based console device, if any, associated with the
current Java virtual machine. The Console class was added to
java.io by JDK 6.
• It is used to read from and write to the console, if one exists.
• Console is primarily a convenience class because most of its
functionality is available through System.in and System.out.
However, its use can simplify some types of console
interactions, especially when reading strings from the console.
Console Class - 2
• Console supplies no constructors. Instead, a Console object is
obtained by calling System.console( ), which is shown here:
• static Console console( )
• If a console is available, then a reference to it is returned. Otherwise,
null is returned. A console will not be available in all cases. Thus, if
null is returned, no console I/O is possible.
• It provides methods to read text and password. If you read password
using Console class, it will not be displayed to the user.The
java.io.Console class is attached with system console internally.
• https://www.geeksforgeeks.org/java-io-console-class-java/
Serialization
• Serialization in Java is a mechanism of writing the state of an object
into a byte-stream. 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.
• We must have to implement the Serializable interface for serializing
the object.
Scanner Class

• Scanner reads formatted input and converts it into its binary form.

• Scanner can be used to read input from the console, a file, a string,
or any source that implements the Readable interface or
ReadableByteChannel.

• For example, you can use Scanner to read a number from the
keyboard and assign its value to a variable.
Enumerated Data Type -1
• An enumerated type defines a list of enumerated values. Each value is an identifier. For
example, the following statement declares a type, named MyWeekDays, with values MON,
TUE, WED, THU and FRI in this order.
enum MyWeekDays{MON, TUE, WED, THU, FRI};
• A value of an enumerated type is like a constant and so, by convention, is spelled with all
uppercase letters.
• So, the preceding declaration uses MON, not mon. By convention, an enumerated type is
named like a class with first letter of each word capitalized.
• Once a type is defined, you can declare a variable of that type:
MyWeekDays day1;
Enumerated Data Type -2
• The variable day1 can hold one of the values defined in the enumerated type MyWeekDays or null,
but nothing else. Java enumerated type is type-safe, meaning that an attempt to assign a value
other than one of the enumerated values or null will result in a compile error.
• The enumerated values can be accessed using the syntax
• EnumeratedTypeName.valueName
• For example, the following statement assigns enumerated value BLUE to variable day1:
• day1 = MyWeekDays.THU;

• Note that you have to use the enumerated type name as a qualifier to reference a value such as
THU.
• As with any other type, you can declare and initialize a variable in one statement:
• MyWeekDays color = MyWeekDays.THU;
Type Wrappers -1
• Despite the performance benefit offered by the primitive types, there
are times when you will need an object representation.
• For example, you can’t pass a primitive type by reference to a
method. Also, many of the standard data structures implemented by
Java operate on objects, which means that you can’t use these data
structures to store primitive types.
• To handle these (and other) situations, Java provides type wrappers,
which are classes that encapsulate a primitive type within an object.
Type Wrappers -2
• Character is a wrapper around a char. The constructor for Character is
• Character(char ch)
• Boolean is a wrapper around boolean values. It defines these constructors:
• Boolean(boolean boolValue)
• Boolean(String boolString)
• double doubleValue( )
• float floatValue( )
• int intValue( )
• long longValue( )
• short shortValue( )
Autoboxing, auto-unboxing - 1
• Autoboxing is the process by which a primitive type is automatically
encapsulated (boxed) into its equivalent type wrapper whenever an
object of that type is needed.
• There is no need to explicitly construct an object. Auto-unboxing is
the process by which the value of a boxed object is automatically
extracted (unboxed) from a type wrapper when its value is needed.
There is no need to call a method such as intValue( ) or
doubleValue()
Autoboxing, auto-unboxing - 2
• Autoboxing and auto-unboxing greatly streamline the coding of several
algorithms, removing the tedium of manually boxing and unboxing values.
They also help prevent errors. Moreover, they are very important to
generics, which operate only on objects. Finally, autoboxing makes
working with the Collections Framework (described in Part II) much easier.

• With autoboxing, it is not necessary to manually construct an object in


order to wrap a primitive type. You need only assign that value to a type-
wrapper reference. Java automatically constructs the object for you.

You might also like