0% found this document useful (0 votes)
8 views85 pages

Chapter 4 - File IO

This document discusses Java input/output streams and readers/writers. It explains the different stream classes for reading and writing bytes and characters and how to use streams to read from and write to files and buffers. Example code is provided to demonstrate reading and writing files using FileInputStream, FileOutputStream, BufferedInputStream and BufferedOutputStream.

Uploaded by

sintebeta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views85 pages

Chapter 4 - File IO

This document discusses Java input/output streams and readers/writers. It explains the different stream classes for reading and writing bytes and characters and how to use streams to read from and write to files and buffers. Example code is provided to demonstrate reading and writing files using FileInputStream, FileOutputStream, BufferedInputStream and BufferedOutputStream.

Uploaded by

sintebeta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

Chapter Four

Java Files and I/O Streams

By: Sinodos G.

1
Introduction

 Java Input and Output is used to process the input and


produce the output.

 Java uses the concept of stream to make I/O operation


fast.

 The java.io package contains all the classes required for


input and output operations and it contains classes that
perform input and output.

 In Java, I/O classes are differentiated according to the


type of data being read or written.

2
Cont’d …
 Byte oriented and numeric data is written with
output streams and read with input streams.

 Character data, that is text, is written with writers


and read with readers.

 Whether you use streams or readers and writers


depends on the type of data you're dealing with.

 All text data, especially non-ASCII text, should be


passed through a reader or writer.

3
Cont’d …
 The two main stream classes are
• java.io.InputStream
• java.io.OutputStream

 The two main reader and writer classes are:


• java.io.Reader and
• java.io.Writer

 These are abstract base classes for many different


subclasses with more specialized abilities.

4
Java Stream
 a sequence of data [composed of bytes] of
undetermined length.

 Java creates three streams automatically. All these


streams are attached with console.

• System.out: standard output stream


• System.in: standard input stream
• System.err: standard error stream

5
Cont’d …
 Let's see the code to print output and error
message to the console.
 System.out.println("simple message");
 System.err.println("error message");

 Let's see the code to get input from console.


• int i=System.in.read();
• //returns ASCII code of 1st character

 System.out.println((char)i);
• //it will print the character

6
Java Stream Classes
 Most java stream classes are part of the java.io package

 The two main classes are java.io.InputStream and


java.io.OutputStream.

 OutputStream:
 Java application uses an output stream to write data
to a destination, it may be a file, an array, peripheral
device or socket.

 InputStream:
 Java application uses an input stream to read data
from a source, it may be a file, an array, peripheral
device or socket.
7
Cont’d …

8
Cont’d …
 Some list of input and output java Streams :-

9
Output Stream
• It is the super class of all classes representing an
output stream of bytes.
• An output stream accepts output bytes and sends
them to some sink.

 Methods of Output stream Class


• Write (int): used to write a byte to the current output
stream.
• Write (byte []): is used to write an array of byte to the
current output stream.
• Flush (): Flushes the current output stream.
• Close (): Used to close the current output stream.

10
Input Stream class

• It is the super class of all classes representing an input


stream of bytes.

 Methods of Input Stream Class


• int read(): reads the next byte of data from the input
stream. It returns -1 at the end of file.

• available (): returns an estimate of the number of


bytes that can be read from the current input stream.

• close (): is used to close the current input stream.

11
File
 A collection of information that is stored on a
computer and assigned a particular name.

 Every file has a name.

 A file name often ends with a special suffix that


indicates the kind of data it contains or the format
in which it has been stored.

 This suffix is known as a file extension.

 lists some common file extensions.

12
Cont’d …
 Files can be classified into two depending on the format
that is used.

 Text files and


 Binary files

 Text files: can be edited using simple text editors.

 Text files are often stored using the .txt extension, but
other file formats are also text formats, including .java
and .html files

13
Cont’d …
Binary files:
• are stored using an internal format that requires
special software to process.

• To access a file from inside a Java program, you


need to construct an internal object that will
represent the file.
File f = new File (“Computer.txt");

• Once you’ve constructed the object, you can


call a number of methods to manipulate the file.

14
Example:-
 The following program calls a method that determines whether
a file exists, whether it can be read, what its length is and what
its absolute path is.

15
Useful class of FileObjects

16
Java FileOutputStream Class
 Java FileOutputStream is an output stream used for
writing data to a file.

 Used to :
 write primitive values into a file
 write byte-oriented as well as character-oriented data
 For character-oriented data, it is preferred to use
FileWriter than FileOutStream.

Declaration
 declaration into java.io.FileOutputStream class
 public class FileOutputStream extends OutputStream

17
Methods:
 finalize(): It is used to clean up the connection with
the file output stream.

 write(byte[] ary): It is used to write ary.length bytes


from the byte array to the file output stream.

 write(byte[] ary, int len): It is used to write len bytes


from the byte array starting at offset off to the file
output stream.

 write(int b): It is used to write the specified byte to


the file output stream.

 close(): It is used to closes the file output stream.

18
Example:

19
Example 2

20
FileInputStream Class
 FileInputStream class obtains input bytes from a file.
 It is used for reading byte-oriented data (streams of
raw bytes) such as image data, audio, video etc.

 You can also read character-stream data. But, for


reading streams of characters, it is recommended to
use FileReader class.

 It’s declaration is for java.io.FileInputStream

 public class FileInputStream extends InputStream

21
FileInputStream class methods
 available(): It is used to return the estimated number
of bytes that can be read from the input stream.
 read(): It is used to read the byte of data from the
input stream.
 read(byte[] b): It is used to read up to b.length bytes
of data from the input stream.
 read(byte[] b, int len): It is used to read up to len
bytes of data from the input stream.
 finalize(): It is used to ensure that the close method
is call when there is no more reference to the file
input stream.
 close(): It is used to closes the stream.
22
Example: read single (first) character

23
Example 2

24
Java Buffered Stream
BufferedOutputStream Class
• Used for buffering an output stream.
• Internally uses buffer to store data.
• Adds more efficiency than to write data directly into
a stream. So, it makes the performance fast.

 Syntax:
OutputStream os new BufferedOutputStream(new
FileOutputStream("D:\\IO Package\\test.txt"));

25
Constructors

 BufferedOutputStream(OutputStream os)
 Used for writing the data to the specified
output stream.

 BufferedOutputStream(OutputStream os, int size)


 Used for writing the data to the specified
output stream with a specified buffer size.

26
Methods
 write (int b):
• It writes the specified byte to the buffered output
stream.
 write(byte[] b, int off, int len):
• It write the bytes from the specified byte-input stream
into a specified byte array, starting with the given
offset

 flush():
• It flushes the buffered output stream.
• Flushes the data of one stream and send it into
another. It is required if you have connected the one
stream with another.
27
Example

28
Cont’d …
BufferedInputStream Class

• Used to read information from stream.

• Internally uses buffer mechanism to make the


performance fast.

• When the bytes from the stream are skipped or read,


the internal buffer automatically refilled from the
contained input stream, many bytes at a time.

• When a BufferedInputStream is created, an internal


buffer array is created.
29
Example

30
Sequence Streams

SequenceInputStream Class
• Used to read data from multiple streams.

• It reads data sequentially (one by one).

• Declared in Java.io.SequenceInputStream class

• public class SequenceInputStream extends InputStream

31
Cont’d …
Constructors:
SequenceInputStream(InputStream s1, InputStream s2):
• creates a new input stream by reading
the data of two input stream in order,
first s1 and then s2.
SequenceInputStream(Enumeration e):
• creates a new input stream by reading
the data of an enumeration whose type
is InputStream.

32
Example1:

33
Example: writing the data of two files lab.txt and lab1.txt into
another file named student.txt

34
Cont’d …

 SequenceInputStream: using enumeration


 Used to read the data from more than two files.
 It can be obtained by calling elements () method of the
Vector class.

Example: Reading data from 4 files using Enumeration: a.txt,


b.txt, c.txt and d.txt.

35
36
Java Array Stream Class
 Java ByteArrayOutputStream
 Used to write common data into multiple files.

 Data is written into a byte array which can be written to


multiple streams later.

 Holds a copy of data and forwards it to multiple streams.

 The buffer automatically grows according to data.

37
Cont’d …
Constructor:
 ByteArrayOutputStream()
• Creates a new byte array output stream with the
initial capacity of 32 bytes, though its size increases if
necessary.

 ByteArrayOutputStream(int size)
• Creates a new byte array output stream, with a
buffer capacity of the specified size, in bytes.

38
Example

39
Cont’d …
ByteArrayInputStream Class
 It is a composed of two words: ByteArray and
InputStream.

 Used to read byte array as input stream.

 It contains an internal buffer which is used to read


byte array as stream. In this stream, the data is read
from a byte array.

 The buffer automatically grows according to data.

40
Constructors
 ByteArrayInputStream(byte[] ary)
• Creates a new byte array input stream which uses ary
as its buffer array.

 ByteArrayInputStream(byte[] ary, int len)


• Creates a new byte array input stream which uses ary
as its buffer array that can read up to specified len
bytes of data from an array.

41
Methods
 int available():- It is used to return the number of
remaining bytes that can be read from the input
stream.
 int read():- It is used to read the next byte of data
from the input stream.
 int read(byte[] ary, int len): It is used to read up to
len bytes of data from an array of bytes in the input
stream.
 reset(): It is used to reset the buffer of a byte array.
 close(): It is used for closing a ByteArrayInputStream.
42
Example

43
Exercise
 Write the following information at
D://Student//Ajava//Exercise using Any output Stream.

 Information:
 Java is a high level, robust and secured programming
language.

 Read the above Information using any Input stream

44
Java Data Streams
Java DataOutputStream Class
 Allows an application to write primitive Java data
types to the output stream in a machine
independent way.

 Java application generally uses the data output


stream to write data that can later be read
by a data input stream.
 Declared in java.io.DataOutputStream class
 public class DataOutputStream extends
FilterOutputStream implements DataOutput

45
Example

46
Cont’d …
Java DataInputStream Class

 Allows an application to read primitive data from the


input stream in a machineindependent way.

 Java application generally uses the data output stream


to write data that can later be read by a data input
stream.

 Declared in java.io.DataInputStream class

 public class DataInputStream extends FilterInputStream


implements DataInput

47
Example:

48
Reading Assignment

• Java Filter Stream


• Permission Stream
• FileWriter Class
• FileReader Class
• PrintStream Class
• PrintWriter class
• Printeader class
49
Java Permission Stream
 Java provides a number of method calls to check and
change the permission of a file, such as a read-only file
can be changed to have permissions to write.

 File permissions are required to be changed when the


user want to restrict the operations permissible on a file.

 Example: a file permission can be changed from write to


read-only because the user no longer want to edit the
file.

 A file can be in any combination of following


permissible permissions.

50
Cont’d …
 A file can be in any combination of following
permissible permissions:

 Executable: Tests whether the application can execute


the file denoted by this abstract path name.
• canExecute()

 Readable: Tests whether the application can read the


file denoted by this abstract path name.
• canRead()

 Writable: Tests whether the application can modify the


file denoted by this abstract path name.
• canWrite()

51
Cont’d …
 Java FilePermission Class
• Java FilePermission class contains the permission related
to a directory or file.
• All the permissions are related with path. The path can be
of two types.
• D:\\IO\\-: It indicates that the permission is associated with
all sub directories and files recursively.
• D:\\IO\\*: It indicates that the permission is associated with
all directory and files within this directory excluding sub
directories.

• It declared in Java.io.FilePermission class


 security. PermissionCollection
52
Cont’d …

53
Cont’d …
 Changing file permissions
 A file can have any combinations of the following
permissions:

 Executable
• setExecutable()

 Readable
• setReadable()

 Writable
• setWritable()

54
Cont’d ….

55
Java FileWriter Class
 a subclass of Writer abstract class and it is used to write
a character, character array or a String to a file.
 It is character-oriented class which is used for file
handling in java.
 Unlike FileInputStream class, you don't need to convert
string into byte array because it provides method to
write string directly.
 Declared in Java.io.FileWriter class:

 public class FileWriter extends OutputStreamWriter

56
Cont’d …
Constructor
 FileWriter (String file):
• Creates a new file. It gets file name in string.

 FileWriter (File file):


• Creates a new file. It gets file name in File object.

Methods
 flush()
 write(int c)
 write(char[])
 write(String str)
 close()
57
Example: FileWriter class.

58
Java FileReader Class

• Used to read data from the file.

• It returns data in byte format like FileInputStream


class.

• It is character-oriented class which is used for file


handling in java.

• Declaration in Java.io.FileReader class

59
Cont’d …
 FileReader(String file)
• It gets filename in string. It opens the given file in read
mode. If file doesn't exist, it throws

• FileNotFoundException.

 FileReader(File file)
• It gets filename in file instance. It opens the given file in
read mode. If file doesn't exist, it

• throws FileNotFoundException.

60
Cont’d …
 Methods
• available()
 gives the remaining number of bytes available to read
from this input stream.
• read()
 reads one character at a time from this input character
stream.
• read(char[])
 reads a whole character array at a time from this input
character stream.
• close()
 closes this input stream and also frees any resources
connected with this input stream.
61
Example: reading the data from the text file test1.txt using
Java FileReader class.

62
Java PrintStream Class
 provides methods to write data to another stream.
 write data not only in terms of characters but also in
terms of primitive data types
 like int, float, long, double and even an Object.

 PrintStream class can be wrapped around any


OutputStream or a Writer class, to write data to a file.

 The PrintStream class automatically flushes the data so


there is no need to call flush ()

63
Cont’d …
 Constructors

 PrintWriter(File file) Methods

 PrintWriter(OutputStream os) • flush()


• write()
 PrintWriter(Writer w) • write(byte[])
• print(char c)
• print(int i)
• println(long l)
• println(float f)

64
Example:

65
Directories in Java
 A directory is a File which can contain a list of
other files and directories.

 Use file object to create directories, to list down


files available in a directory.

66
Creating Directories
 There are two useful methods, which can be used to
create directories: -

 The mkdir( ): method creates a directory, returning


true on success and false on failure.
• Failure indicates that the path specified in the File
object already exists, or that the directory cannot be
created because the entire path does not exist yet.

 The mkdirs(): method creates both a directory and


all the parents of the directory. The Following
 Example creates "D:\\DDIT\\Abebe\\Tesfaye":

67
Example

68
Listing Directories
 List ( ) method: Provided by File object to list down
all the files and directories available in a directory.

69
Exercise
1. Write a program that creates the following
directories.

D://Student//Class//Java//Handout//Chapter1.doc

2. Write a program, that create first the above


directories and write the following Information
to the given file name. “Hello Students”

70
Solution Question Number 1:

71
Solution Question Number 2

72
Serialization
 Java provides a mechanism, called object
serialization where an object can be represented as a
sequence of bytes that includes:-
 The object's data as well as information about the
object's type and

 The types of data stored in the object.

 It is mainly used in Hibernate, RMI, JPA, EJB and JMS


technologies.

 The reverse operation of


serialization is called deserialization.
73
Cont’d …
 Classes ObjectInputStream and ObjectOutputStream are
high-level streams that contain the methods for serializing
and deserializing an object.

 In java serialization:
• The ObjectOutputStream: used for serializable (to write
objects) and
• The ObjectInputStream: used for deserializable (to read
object)
• The class must implement the java.io.Serializable
interface.
• When serializing an object to a file, the standard
convention in Java is to give the file a .ser extension.
74
Cont’d …
 Advantage of Java Serialization
• Used to convert objects into stream.

• It is mainly used to travel object's state on the network


(known as marshaling)

75
java.io.Serializable Interface

• Serializable is a marker interface (has no data member


and method).

• It is used to "mark" java classes so that objects of these


classes may get certain capability.

• It must be implemented by the class whose object you


want to persist.

• The String class and all the wrapper classes’ implements


java.io.Serializable interface by default.

76
Cont’d …
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

• In the above example, Student class implements Serializable


interface. Now its objects can be converted into stream.

77
ObjectOutputStream class

 The ObjectOutputStream class is used to write


primitive data types and Java objects to an
OutputStream.

 Only objects that support the java.io.Serializable


interface can be written to streams.

Constructor

 public ObjectOutputStream(OutputStream out)


• creates an ObjectOutputStream that writes to the
specified OutputStream.

78
Important Methods

 public final void writeObject(Object obj)


 writes the specified object to the
ObjectOutputStream.

 public void flush()


 flushes the current output stream.

 public void close()


 closes the current output stream.

79
Example: Serialization

80
Deserialization

 Deserialization is the process of reconstructing the


object from the serialized state.
 It is the reverse operation of serialization.

 ObjectInputStream class
• An ObjectInputStream deserializes objects written using an
ObjectOutputStream.

 Constructor
 public ObjectInputStream(InputStream in)
• creates an ObjectInputStream that reads from the specified
InputStream

81
 Methods
 readObject() : reads an object from the input stream.
 close(): closes ObjectInputStream.

82
The transient Keyword
 Java transient keyword is used in serialization. If you
define any data member as transient, it
will not be serialized

Example: I have declared a class as Student, it has


three data members’ id, name and age.
• If you serialize the object, all the values will be
serialized but I don't want to serialize one
value.
• e.g. age then we can declare the age data member
as transient.

83
Example:

84
Question

85

You might also like