Unit 3
Unit 3
© Ganapathi Nayak K
1
Files and Directories
File
Class present in the package java.io
Deals with files and file system (and not streams)
Does not specify how information is stored in and retrieved from files
Describes the properties of the file itself
File object: Obtain and manipulate information associated with a disk file
Permissions, Time, Date, Directory path etc.
© Ganapathi Nayak K
2
Files and Directories
File (Continued …)
Constructors used to create File objects (new File instances)
File (String directoryPath)
File (String directoryPath, String fileName)
File (File dirObj, String fileName)
File (URI URIObj)
Examples:
File f1 = new File (“/”);
File f2 = new File (“/Dir1”, “sample1.txt”);
File f3 = new File (f1, “sample2.txt”);
© Ganapathi Nayak K
3
Files and Directories
File Methods
Method Description
© Ganapathi Nayak K
4
Files and Directories
Method Description
© Ganapathi Nayak K
5
Files and Directories
Method Description
© Ganapathi Nayak K
6
Files and Directories
Method Description
setWritable
boolean (boolean writable, Sets/resets the invoking file to writable
boolean ownerOnly)
setExecutable
boolean (boolean writable, Sets/resets the invoking file to executable
boolean ownerOnly)
© Ganapathi Nayak K
7
Files and Directories
Directories
A File that contains list of other files and directories
Methods available
Method Description
© Ganapathi Nayak K
8
Files and Directories
Directories (Continued …)
Using FilenameFilter: Select files that match a certain pattern
Syntax: String[] list (FilenameFilter FFObj)
FFObj is an object that implements FilenameFilter interface
FilenameFilter (interface) defines a method accept()
Syntax: boolean accept (File directory, String filename)
Returns true for files in the directory specified by directory to be included in the list (of
files to be filtered)
© Ganapathi Nayak K
9
Files and Directories
Directories (Continued …)
The listFiles() alternative
Returns file list as an array of File objects instead of strings
Form 1: File[] listFiles ()
Form 2: File[] listFiles (FilenameFilter FFObj)
Form 3: File[] listFiles (FileFilter FObj)
FileFilter (abstract class) defines only a single method called accept(), which is called
once for each file in the list
boolean accept (File path)
Returns true for files to be included in the list (those which match the path argument);
false for others
© Ganapathi Nayak K
10
Files and Directories
Creating Directories
The mkdir() method
Createsa directory; returns true on success, false on failure
Syntax: public boolean mkdir()
Example: File f = new File (“newdir”);
boolean b = f.mkdir();
OR
new File (“newdir”).mkdir();
© Ganapathi Nayak K
11
Streams
Stream
A logical entity that either produces or consumes information
Linked to a physical device by the Java I/O system
All streams behave in the same manner, even if the actual physical devices they are
linked to differ
The java.io package has a number of classes and interfaces to handle I/O
© Ganapathi Nayak K
12
Streams
© Ganapathi Nayak K
13
Streams
© Ganapathi Nayak K
14
Streams
© Ganapathi Nayak K
15
Streams
InputStream
© Ganapathi Nayak K
16
Streams
InputStream (Continued …)
Method Description
© Ganapathi Nayak K
17
Streams
InputStream (Continued …)
Method Description
void reset ( ) ✓ Resets the input pointer to the previously set mark.
© Ganapathi Nayak K
18
Streams
OutputStream
© Ganapathi Nayak K
19
Streams
OutputStream (Continued …)
Method Description
void write (byte buffer[ ]) ✓ Writes a complete array of bytes to an output stream.
FileInputStream
Creates an InputStream to read bytes from a file
Constructors (can throw FileNotFoundException)
FileInputStream(String filePath) // full path name of the file
Ex: FileInputStream f0 = new FileInputStream (“test.txt”);
FileInputStream(File fileObj) // file object describes the file
Ex: File f = new File (“test.txt”);
FileInputStream f1 = new FileInputStream(f);
© Ganapathi Nayak K
21
Byte Streams
FileOutputStream
Creates an OutputStream to write bytes to a file
Constructors (can throw IOException in case of read-only files)
FileOutputStream(String filePath) // full path name of the file
Ex: FileOutputStream f0 = new FileOutputStream (“test.txt”);
FileOutputStream(File fileObj) // file object describes the file
Ex: File f = new File (“test.txt”);
FileOutputStream f1 = new FileOutputStream(f);
FileOutputStream(String filePath, boolean append)
Ex: FileOutputStream f2 = new FileOutputStream (“test.txt”, true);
FileOutputStream(File fileObj, boolean append)
Ex: File f = new File (“test.txt”);
FileOutputStream f3 = new FileOutputStream(f, false);
© Ganapathi Nayak K
22
Byte Streams
ByteArrayInputStream
Implements an input stream that uses a byte array as the source
Fields (protected)
Field Description
int count Index one greater than the last valid character in the input stream buffer
int pos Index of the next character to be read from the stream buffer
© Ganapathi Nayak K
23
Byte Streams
ByteArrayInputStream (Continued …)
Constructors
ByteArrayInputStream (byte array[])
– Creates a stream from the specified byte array that uses buf as its internal buffer
ByteArrayInputStream (byte array[], int start, int numBytes)
– Creates a stream from the specified part of the byte array that uses buf as its
internal buffer
Example:
String temp = “Manipal”;
byte b[] = temp.getBytes();
ByteArrayInputStream b1 = new ByteArrayInputStream(b);
ByteArrayInputStream b2 = new ByteArrayInputStream(b, 1, 3);
© Ganapathi Nayak K
24
Byte Streams
ByteArrayOutputStream
Implements an output stream that uses a byte array as the destination
Fields (protected)
Field Description
© Ganapathi Nayak K
25
Byte Streams
ByteArrayOutputStream (Continued …)
Constructors
ByteArrayOutputStream()
– A buffer of 32 bytes is created
ByteArrayOutputStream(int numBytes)
– A buffer of size numBytes is created
– Number of bytes held by the buffer is contained in the protected count field of
ByteArrayOutputStream
© Ganapathi Nayak K
26
Byte Streams
BufferedOutputStream
PushbackInputStream
© Ganapathi Nayak K
27
Byte Streams
BufferedInputStream
Wrap any InputStream into buffered stream
Fields (protected)
Field Description
int count Index one greater than the last valid byte in buf
Maximum read ahead allowed after a call to the mark method before
int marklimit
subsequent calls to the reset method
int markpos Value of the pos field at the time the last mark method was called
© Ganapathi Nayak K
28
Byte Streams
BufferedInputStream (Continued …)
Constructors
BufferedInputStream (InputStream in)
– Creates a buffered input stream
– Default buffer size (8192 characters)
© Ganapathi Nayak K
29
Byte Streams
BufferedOutputStream
Similar to any OutputStream except that flush() method is added
To physically write data buffers
Fields (protected)
Field Description
© Ganapathi Nayak K
30
Byte Streams
BufferedOutputStream (Continued …)
Constructors
BufferedOutputStream (OutputStream out)
– Creates a new buffered output stream to write data to the specified output stream
– Default buffer size (8192 characters)
© Ganapathi Nayak K
31
Byte Streams
PrintStream
Provides all output capabilities of System.out
Implements Appendable, Closeable and Flushable interfaces
Fields
protected OutputStream out
Constructors
PrintStream (OutputStream out)
PrintStream (OutputStream out, boolean flushOnNewline)
PrintStream (OutputStream out, boolean flushOnNewline, String charSet)
throws UnsupportedEncodingException
© Ganapathi Nayak K
32
Byte Streams
PrintStream (Continued …)
Write output to a file
Can be created from a File object or by specifying a file name
Existing file will be deleted
Constructors
PrintStream (File outputFile) throws FileNotFoundException
PrintStream (File outputFile, String charSet)
throws FileNotFoundException, UnsupportedEncodingException
PrintStream (String outputFileName) throws FileNotFoundException
PrintStream (String outputFileName, String charSet)
throws FileNotFoundException, UnsupportedEncodingException
© Ganapathi Nayak K
33
Byte Streams
PrintStream (Continued …)
Supports print() and println() methods
Ifan argument is not a primitive type, it calls the object’s toString() method and then
display the result
The printf() method (added with the release of JDK 5) supports formatted
output
Constructors
© Ganapathi Nayak K
34
Byte Streams
DataOutputStream
Write primitive data to a stream
Constructor
DataOutputStream (OutputStream out)
– Creates a data output stream that uses the specified output stream
Defines methods to convert values of a primitive type into a byte sequence and then
write it to the output stream
– final void writeDouble (double value) throws IOException
– final void writeBoolean (boolean value) throws IOException
– final void writeInt (int value) throws IOException
© Ganapathi Nayak K
35
Byte Streams
DataInputStream
Read primitive data from a stream
Constructor
DataInputStream (InputStream is)
– Creates a data input stream that uses the specified input stream
Defines methods to read a sequence of bytes from the stream and then convert them
into values of a primitive type
– double readDouble () throws IOException
– boolean readBoolean () throws IOException
– int readInt () throws IOException
© Ganapathi Nayak K
36
Byte Streams
RandomAccessFile
Encapsulates a random-access file
Not derived from InputStream or OutputStream classes
Implements DataInput and DataOutput interfaces
Supports positioning of file pointer within the file
© Ganapathi Nayak K
37
Byte Streams
RandomAccessFile
Constructors
RandomAccessFile (File fileObj, String access) throws IOException
RandomAccessFile (String fileName, String access) throws IOException
Access modes:
‘r’ – read only
‘rw’ – read-write
‘rws’ - opened for read-write, updates file’s data and metadata
‘rwd’ - opened for read-write, updates only file’s data
(metadata is updated on file closure)
© Ganapathi Nayak K
38
Byte Streams
RandomAccessFile (Continued …)
Method Description
© Ganapathi Nayak K
39
Byte Streams
RandomAccessFile (Continued …)
Method Description
© Ganapathi Nayak K
40
Byte Streams
RandomAccessFile (Continued …)
Method Method
© Ganapathi Nayak K
41
Character Streams
Reader
© Ganapathi Nayak K
42
Character Streams
Reader (Continued …)
Reader – an abstract class – defines streaming character input
Method Description
© Ganapathi Nayak K
43
Character Streams
Reader (Continued …)
Method Description
void reset ( ) ✓ Resets the input pointer to the previously set mark.
© Ganapathi Nayak K
44
Character Streams
Writer
© Ganapathi Nayak K
45
Character Streams
Writer (Continued …)
Writer – an abstract class – defines streaming character output
Method Description
© Ganapathi Nayak K
46
Character Streams
Writer (Continued …)
Method Description
void write (char ch) ✓ Writes a single character to the invoking output stream.
write
✓ Writes a sub-range of numChars characters from the
abstract (char buffer[ ],
array buffer, beginning at buffer[offset] to the invoking
void int offset,
output stream.
int numChars)
© Ganapathi Nayak K
47
Character Streams
Writer (Continued …)
Method Description
void write (String str) ✓ Writes str to the invoking output stream.
© Ganapathi Nayak K
48
Character Streams
FileReader
Creates a Reader that can be used to read from a file
Fields (protected)
Object lock – Object used to synchronize operations on this stream
© Ganapathi Nayak K
49
Character Streams
FileWriter
Creates a Writer that can be used to write to a file
Fields (protected)
Object lock – Object used to synchronize operations on this stream
© Ganapathi Nayak K
50
Character Streams
CharArrayReader
Implementation of the input stream that uses character array as the source
Fields (protected)
Field Description
© Ganapathi Nayak K
51
Character Streams
CharArrayReader (Continued …)
Constructors (can throw IOException)
CharArrayReader (char array[])
– Creates a character array reader from the specified array of characters
CharArrayReader (char array[], int start, int numChars)
– Creates a character array reader from the specified part of the array of characters
© Ganapathi Nayak K
52
Character Streams
CharArrayWriter
Implementation of the output stream that uses character array as the
destination
Fields (protected)
Field Description
© Ganapathi Nayak K
53
Character Streams
CharArrayWriter (Continued …)
Constructors (can throw IOException)
CharArrayWriter ()
– Creates a character array reader with a default size (8192 bytes)
CharArrayWriter (int numChars)
– Creates a character array reader with the specified size
© Ganapathi Nayak K
54
Character Streams
BufferedReader
Improves performance by buffering input
Constructors (can throw IOException)
BufferedReader (Reader inputStream)
– Creates a buffered stream using default buffer size (8192 characters)
BufferedReader (Reader inputStream, int bufSize)
– Size of the buffer is passed in bufSize
© Ganapathi Nayak K
55
Character Streams
BufferedWriter
Improves performance by buffering output
Constructors (can throw IOException)
BufferedWriter (Writer outputStream)
– Creates a buffered stream using default buffer size (8192 characters)
BufferedWriter (Writer outputStream, int bufSize)
– Size of the buffer is passed in bufSize
© Ganapathi Nayak K
56
Predefined Streams
© Ganapathi Nayak K
57
Predefined Streams
Example
InputStreamReader in = new InputStreamReader (System.in);
BufferedReader br = newBufferedReader (in);
OR
BufferedReader br = newBufferedReader (new InputStreamReader(System.in));
br is the character-based stream that is linked to the console through System.in
© Ganapathi Nayak K
58
Predefined Streams
Reading strings
Usage
String readLine() throws IOException
Example
String s = br.readLine();
© Ganapathi Nayak K
59
Predefined Streams
© Ganapathi Nayak K
60
Serialization
Information about the objects type and types of data stored in the object
JVM independent
Serializable Interface
Defines no members
© Ganapathi Nayak K
63
Serialization
ObjectOutput Interface
Extends DataOutput interface and supports object serialization
Method Description
void write (byte buffer[ ]) ✓ Writes an array of bytes to the invoking stream.
write (byte buffer[ ], ✓ Writes a subrange of numBytes bytes from the array
void
int offset, int numBytes) buffer, beginning at buffer[offset].
void writeObject (Object obj) ✓ Writes object obj to the invoking stream.
ObjectOutputStream Class
Extends OutputStream class and implements ObjectOutput interface
Responsible for writing objects to a stream
Constructor
ObjectOutputStream (OutputStream out) throws IOException
Argument out is the output stream to which serialized object will be written
© Ganapathi Nayak K
65
Serialization
Method Description
void write (byte buffer[ ]) ✓ Writes an array of bytes to the invoking stream.
© Ganapathi Nayak K
66
Serialization
Method Description
void writeChars (String str) ✓ Writes the characters in str to the invoking stream.
© Ganapathi Nayak K
67
Serialization
Method Description
final void writeObject (Object obj) ✓ Writes obj to the invoking stream.
© Ganapathi Nayak K
68
Serialization
ObjectInput Interface
Extends DataInput interface and supports object serialization
Method Description
Method Description
© Ganapathi Nayak K
70
Serialization
ObjectInputStream Class
Constructor
ObjectInputStream (InputStream in) throws IOException
Argument in is the input stream from which serialized object will be read
© Ganapathi Nayak K
71
Serialization
Method Description
© Ganapathi Nayak K
72
Serialization
Method Description
char readChar ( ) Reads and returns a char from the invoking stream.
double readDouble ( ) Reads and returns a double from the invoking stream.
float readFloat ( ) Reads and returns a float from the invoking stream.
int readInt ( ) Reads and returns an int from the invoking stream.
long readLong ( ) Reads and returns a long from the invoking stream.
short readShort ( ) Reads and returns a short from the invoking stream.
© Ganapathi Nayak K
73
Serialization
Method Description
final Object readObject ( ) Reads and returns an object from the invoking stream.
© Ganapathi Nayak K
74
Serialization
Implementation
Create a class to implement Serializable interface
Serialization
Create a FileOutputStream to refer to a file named “Student.ser”
Create an ObjectOutputStream for this file stream
Use writeObject() method of ObjectOutputStream to serialize the object
Flush and close the ObjectOutputStream
Deserialization
Create a FileInputStream to refer to the file named “Student.ser”
Create an ObjectInputStream for this file stream
Use readObject() method of ObjectInputStream to deserialize the object
Close the ObjectInputStream
© Ganapathi Nayak K
75
The End
© Ganapathi Nayak K
76