You are on page 1of 23

IO Streams and File System

IO streams overview


Reading and Writing:
Files, primitive data types and objects

IO Serialization

Wednesday, March 25, 2020


Streams
• 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. Thus, the same I/O classes and
methods can be applied to any type of device.

• All these streams represent an input source and an output destination


The Concept of a Stream
 A stream is a flow of data. The data might be characters, numbers, or
bytes consisting of binary digits.
 If the data flows into your program, the stream is called an input
stream.
 If the data flows out of your program, the stream is called an output
stream.
 For example, if an input stream is connected to the keyboard, the data
flows from the keyboard into your program. If an input stream is
connected to a file, the data flows from the file into your program.
Figure below illustrates some of these streams.
Byte Streams and Character Streams
 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.
 At the lowest level, all I/O is byte-oriented. The character-based
streams simply provide a convenient and efficient means for handling
characters.
Byte Stream
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 between various
devices, such as:
 disk files,
 network connections, and
 even memory buffers.
To use the stream classes, we must import java.io.

Wednesday, March 25, 2020 5


Byte Stream cont…
The abstract classes InputStream and OutputStream
define several key methods that the other stream
classes implement.
Two of the most important are read( ) and write( ),
which, respectively, read and write bytes of data.
Both methods are declared as abstract inside
InputStream and OutputStream.
They are overridden by derived stream classes.

Wednesday, March 25, 2020 6


Wednesday, March 25, 2020 7
Character Stream
Character streams are defined by using two class hierarchies.
At the top are two abstract classes,
 Reader and
 Writer,
which define several key methods that the other stream classes
implement.
These abstract classes handle Unicode character streams.
Java has several concrete subclasses of each of these.
Two of the most important methods are read( ) and write( ),
which read and write characters of data, respectively.
These methods are overridden by derived stream classes.

Wednesday, March 25, 2020 8


Wednesday, March 25, 2020 9
The Predefined Streams
java.lang package defines a class called System,
which encapsulates several aspects of the run-time
environment.
Using some of its methods, you can do the settings of
various properties associated with the system.
System also contains three predefined stream
variables, in, out, and err.
These fields are declared as public, static and final
within System.
They can be used by any other part of the program and
without reference to a specific System object.
Wednesday, March 25, 2020 10
The Predefined Streams cont…
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.
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, used to read and write characters from
and to the console.

Wednesday, March 25, 2020 11


File Class
The File class is intended to provide an abstraction
that deals with most of the machine-dependent
complexities of files and path names in a machine-
independent fashion.
The filename is a string.
The File class is a wrapper class for the file name and
its directory path.

12
java.io.File

+File(pathname: String) Creates a File object for the specified pathname. The pathname may be a
directory or a file.
+File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a
filename or a subdirectory.
+File(parent: File, child: String) Creates a File object for the child under the directory parent. parent is a File
object. In the preceding constructor, the parent is a string.
+exists(): boolean Returns true if the file or the directory represented by the File object exists.
+canRead(): boolean Returns true if the file represented by the File object exists and can be read.
+canWrite(): boolean Returns true if the file represented by the File object exists and can be written.
+isDirectory(): boolean Returns true if the File object represents a directory.
+isFile(): boolean Returns true if the File object represents a file.
+isAbsolute(): boolean Returns true if the File object is created using an absolute path name.
+isHidden(): boolean Returns true if the file represented in the File object is hidden. The exact
Obtaining file definition of hidden is system-dependent. On Windows, you can mark a file
properties and hidden in the File Properties dialog box. On Unix systems, a file is hidden if
its name begins with a period character '.'.
manipulating file +getAbsolutePath(): String Returns the complete absolute file or directory name represented by the File
object.
+getCanonicalPath(): String Returns the same as getAbsolutePath() except that it removes redundant
names, such as "." and "..", from the pathname, resolves symbolic links (on
Unix platforms), and converts drive letters to standard uppercase (on Win32
platforms).
+getName(): String Returns the last name of the complete directory and file name represented by
the File object. For example, new File("c:\\book\\test.dat").getName() returns
test.dat.
+getPath(): String Returns the complete directory and file name represented by the File object.
For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.
+getParent(): String Returns the complete parent directory of the current directory or the file
represented by the File object. For example, new
File("c:\\book\\test.dat").getParent() returns c:\book.
+lastModified(): long Returns the time that the file was last modified.
+delete(): boolean Deletes this file. The method returns true if the deletion succeeds.
13
+renameTo(dest: File): boolean Renames this file. The method returns true if the operation succeeds.
Example:
import java.io.*;
class FileDemo {
public static void main(String args[]){
File f1 = new File("a.txt");
System.out.println("File Name: " + f1.getName());
System.out.println("Path: " + f1.getPath());
System.out.println("Is Absolute : " + f1.isAbsolute());
System.out.println("Absolute Path: " + f1.getAbsolutePath());
System.out.println("Parent: " + f1.getParent());
System.out.println(f1.exists() ? "exists" : "does not exist");
System.out.println("Is a Directory: "+ f1.isDirectory());
System.out.println("Is a File: "+ f1.isFile());
System.out.println("Can Write? "+ f1.canWrite());
System.out.println("Can Read? "+ f1.canRead());
System.out.println("File last modified: " + f1.lastModified());
System.out.println("File size: " + f1.length() + " Bytes");
}
}
Wednesday, March 25, 2020 14
Scanner class
 The java.util.Scanner class was used to read strings and primitive values
from the console:
 Scanner s= new Scanner(System.in);
 To read from a file, create a Scanner for a file, as follows:
 Scanner input = new Scanner(new File(filename));
Example:
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("b.txt");
Scanner input = new Scanner(file);
while(input.hasNext()) {
String s = input.nextLine();
System.out.println(s);
}
input.close();
}
}
PrintWriter class
 Thejava.io.PrintWriter class can be used to create a file and write data
to a text file.
 PrintWriter output = new PrintWriter(filename);
 Then, you can invoke the print, println methods on PrintWriter object.
Example:
import java.io.*;
public class PrintWriterDemo {
public static void main(String[] args) throws Exception {
File f = new File("b.txt");
PrintWriter output = new PrintWriter(f);
output.print("Java class ");
output.println(40);
output.print("LPU ");
output.println(85.5);
output.print('a');
output.close();
}
}
Reading and Writing Files
In Java, all files are byte-oriented
FileInputStream and FileOutputStream create byte streams linked
to files
To open a file, create an object of one of these classes, specifying the
name of the file as an argument to the constructor

FileInputStream (String fileName) throws FileNotFoundException


FileOutputStream (String fileName) throws FileNotFoundException
void close( ) throws IOException
int read( ) throws IOException

To read a file, use read( ) method defined by FileInputStream.


To write to a file, use write( ) method defined by FileOutputStream.

Wednesday, March 25, 2020 19


Example:
import java.io.*;
class FRead{
public static void main(String ar[]) throws Exception{
FileInputStream fin=new FileInputStream("abc.txt");
FileOutputStream fout=new FileOutputStream("def.txt");
char c;
c=(char)fin.read();
while(c!='q'){
fout.write(c);
System.out.print(c);
c=(char)fin.read();
}
}
}

Wednesday, March 25, 2020 20


Object Serialization
Object serialization is the mechanism for saving an object,
and its current state, so that it can be used again in another
program
The idea that an object can “live” beyond the program
execution that created it is called persistence
Object serialization is accomplished using the
Serializable interface and the ObjectOutputStream and
ObjectInputStream classes
The writeObject method is used to serialize an object
The readObject method is used to deserialize an object
ObjectOutputStream and ObjectInputStream are
processing streams that must be wrapped around an
OutputStream or an InputStream.
Wednesday, March 25, 2020 21
Object Serialization cont…
Once serialized, the objects can be read again into another
program.
Serialization takes into account any other objects that are
referenced by an object being serialized, saving them too.
Each such object must also implement the Serializable
interface.
Many classes from the Java class library implement
Serializable, including the String class.
The ArrayList class also implements the Serializable
interface, permitting an entire list of objects to be
serialized in one operation.

Wednesday, March 25, 2020 22


Thank You

Wednesday, March 25, 2020 23

You might also like