Object-Oriented Programming: File Handling in Java
Object-Oriented Programming: File Handling in Java
Object-Oriented Programming: File Handling in Java
4
Steps for Using Stream Classes
Input and Output streams are abstract classes and are used for
reading and writing of unstructured sequence of bytes.
The other input and output streams are subclasses of the basic
Input and Output stream class and are used for reading and writing
to a file.
The different types of byte streams can be used interchangeably as
they inherit the structure of Input/Output stream class.
For reading or writing bytes, a subclass of the InputStream or
OutputStream class has to be used respectively.
5
File Class [1-2]
File class directly works with files and the file system.
The files are named using the file-naming conventions of the host
operating system.
These conventions are encapsulated using the File class
constants.
A pathname can be absolute or relative.
In an absolute pathname, no other information is required in order to
locate the required file as the pathname is complete.
In a relative pathname, information is gathered from some other
pathname.
The classes in the java.io package resolve relative pathnames
against the current user directory, which is named by the system
property user.dir.
6
File Class [2-2]
7
Methods of File Class [1-4]
The methods in File class help to manipulate the file on the file
system.
Some of the methods in the File class are:
renameTo(File newname): Names the existing File object with the new
name specified by the variable newname.
delete(): Deletes the file represented by the abstract path name.
exists(): Tests the existence of file or directory denoted by this abstract
pathname.
getPath(): Converts the abstract pathname into a pathname string.
isFile(): Checks whether the file denoted by this abstract pathname is a
normal file.
createNewFile(): Creates a new empty file whose name is the pathname for
this file. It is only created when the file of similar name does not exist.
mkdir(): Creates the directory named by this abstract pathname.
toPath(): Returns a java.nio.file.Path object constructed from the
abstract path.
toURI(): Constructs a file, URI. This file represents this abstract pathname.
8
Methods of File Class [2-4]
The following Code Snippet displays the use of methods of the File
class:
Code Snippet
. . .
File fileObj = new File(“C:/Java/Hello.txt”);
System.out.println(“Path is: “ +fileObj.getPath());
System.out.println(“Name is: “ +fileObj.getName());
System.out.println(“File exists is: “ +fileObj.exists());
System.out.println(“File is: “ +fileObj.isFile());
...
Displays the full path and the filename of the invoking File object.
Checks for the existence of the file and returns true if the file exists,
false if it does not.
isFile() method returns true if called on a file and returns false if
called on a directory.
9
Methods of File Class [3-4]
import java.io.*;
class FileFilter implements FilenameFilter {
String ext;
public FileFilter(String ext) {
this.ext = “.” + ext;
}
public boolean accept (File dir, String fName) {
return fName.endsWith(ext);
}
}
public class DirList {
public static void main (String [] args) {
String dirName = “d:/resources”;
10
Methods of File Class [4-4]
11
FileDescriptor Class
12
DataInput Interface and DataOutput Interface
13
14
Methods of DataInput Interface
try
{
DataInputStream dis = new DataInputStream(System.in);
double d = dis.readDouble();
int num = dis.readInt();
}
catch(IOException e) {}
. . .
15
Methods of DataOutput Interface
16
java.io Package [1-7]
17
java.io Package [2-7]
18
java.io Package [3-7]
The following Code Snippet displays the working of byte streams using
the FileInputStream class and FileOutputStream class: (đọc/ghi
1 byte)
Code Snippet
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamApp {
public static void main(String[] args) throws IOException {
FileInputStream inObj = null;
FileOutputStream outObj = null;
try {
inObj = new FileInputStream(“c:/java/hello.txt”);
outObj = new FileOutputStream(“outagain.txt”);
int ch;
while ((ch = inObj.read()) != -1) {
outObj.write(ch);
19
java.io Package [4-7]
}
} finally {
if (inObj != null) {
inObj.close();
}
if (outObj != null) {
outObj.close();
}
}
}
}
20
java.io Package [5-7]
Writer class.
There are character stream classes that specialize in file I/O
21
java.io Package [6-7]
try {
inObjStream = new FileReader(“c:/java/hello.txt”);
outObjStream = new FileWriter(“charoutputagain.txt”);
int ch;
while ((ch = inObjStream.read()) != -1) {
outObjStream.write(ch);
}
} finally {
if (inObjStream != null) {
inObjStream.close();
}
}
}
22
java.io Package [7-7]
23
Methods of InputStream Class [1-2]
read():
The read() method reads the next bytes of data from the input
24
Methods of InputStream Class [2-2]
mark(int n):
The mark(int n) method marks the current position in the stream
and will remain valid until the number of bytes specified in the
variable, n, is read.
A call to the reset() method will position the pointer to the last
marked position.
public void mark(int readlimit)
skip(long n):
The skip(long n) method skips n bytes of data while reading from
an input stream.
public long skip(long n) throws IOException
reset():
The reset() method rests the reading pointer to the previously set
25
FileInputStream Class [1-3]
File stream objects can be created by either passing the name of the
file or a File object or a FileDescriptor object respectively.
FileInputStream class is used to read bytes from a file.
When an object of FileInputStream class is created, it is also
opened for reading.
FileInputStream class overrides all the methods of the
InputStream class except mark() and reset() methods.
The reset() method will generate an IOException.
Commonly used constructors of this class are as follows:
FileInputStream(String sObj)
FileInputStream(File fObj)
FileInputStream(FileDescriptor fdObj)
26
FileInputStream Class [2-3]
. . .
FileInputStream fileName = new FileInputStream(“Helloworld.txt”);
File fName = new File(“/command.doc”);
FileInputStream fileObj = new FileInputStream(fName);
import java.io.FileInputStream;
import java.io.IOException;
public class FIStream {
public static void main(String argv[]){
try {
27
FileInputStream Class [3-3]
FileInputStream intest;
intest = new FileInputStream(“D:/resources/Client.java”);
int ch;
while ((ch = intest.read()) > -1) {
StringBuffer buf = new StringBuffer();
buf.append((char) ch);
System.out.print(buf.toString());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
28
ByteArrayInputStream Class [1-2]
Code Snippet
. . .
String content = “Hello World”;
Byte [] bObj = content.getBytes();
ByteArrayInputStream inputByte = new ByteArrayInputStream(bObj);
. . .
30
OutputStream Class and its Subclasses
31
Methods in OutputStream Class
write(byte[]
write(byte[]
write(int b) b, int off,
b)
int len)
flush() close()
32
FileOutputStream Class [1-2]
33
FileOutputStream Class [2-2]
34
ByteArrayOutputStream Class
35
Methods in ByteArrayOutputStream Class [1-2]
writeTo(OutputStream out)
toString()
36
Methods in ByteArrayOutputStream Class [2-2]
. . .
String strObj = “Hello World”;
byte[] buf = strObj.getBytes();
ByteArrayOutputStream byObj = new ByteArrayOutputStream();
byObj.write(buf);
System.out.println(“The string is:” + byObj.toString());
. . .
37
Filter Streams [1-8]
streams.
They either transform the data along the way or provide additional
functionality.
FilterInputStream:
The FilterInputStream class overrides all the methods of the
java.io.FilterInputStream class:
protected InputStream in
protected FilterInputStream(InputStream in)
38
Filter Streams [2-8]
package javaioapplication;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
39
Filter Streams [3-8]
import java.io.IOException;
import java.io.InputStream;
public class FilterInputApplication {
public static void main(String[] args) throws Exception {
InputStream inputObj = null;
FilterInputStream filterInputObj = null;
try {
// creates input stream objects
inputObj = new FileInputStream(“C:/Java/Hello.txt”);
filterInputObj = new BufferedInputStream(inputObj);
// reads and prints from filter input stream
System.out.println((char) filterInputObj.read());
System.out.println((char) filterInputObj.read());
// invokes mark at this position
filterInputObj.mark(0);
System.out.println(“mark() invoked”);
System.out.println((char) filterInputObj.read());
System.out.println((char) filterInputObj.read());
} catch (IOException e) {
40
Filter Streams [4-8]
41
Filter Streams [5-8]
FilterOutputStream Class:
The FilterOutputStream class overrides all methods of
of this class.
This creates an output stream filter that exist class over the defined
output stream.
42
Filter Streams [6-8]
Code Snippet
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FilterOutputApplication {
public static void main(String[] args) throws Exception {
OutputStream OutputStreamObj = null;
FilterOutputStream filterOutputStreamObj = null;
FileInputStream filterInputStreamObj = null;
byte[] bufObj = {81, 82, 83, 84, 85};
int i=0;
char c;
43
Filter Streams [7-8]
44
Filter Streams [8-8]
}catch(IOException e){
// checks for any I/O errors
System.out.print(“Close() is invoked prior to write()”);
}finally{
// releases system resources associated with the stream
if(OutputStreamObj!=null)
OutputStreamObj.close();
if(filterOutputStreamObj!=null)
45
Buffered Streams
46
BufferedInputStream Class
47
BufferedOutputStream Class
48
Character Streams [1-4]
Byte stream classes provide methods to handle any type of I/O operations
except Unicode characters.
Character streams provide functionalities to handle character oriented
input/output operations.
They support Unicode characters and can be internationalized.
Reader and Writer are abstract classes at the top of the class hierarchy that
supports reading and writing of Unicode character streams.
All character stream class are derived from the Reader and Writer class.
Reader Class:
Reader class is an abstract class used for reading character streams.
The subclasses of this class override some of the methods present in this
class to increase the efficiency and functionality of the methods.
All the methods of this class throw an IOException.
The read() method returns -1 when end of the file is encountered.
The following are the two constructors for the Reader class:
Reader()
Reader(Object lock)
49
Character Streams [2-4]
Writer Class:
Writer class is an abstract class and supports writing characters into
streams through methods that can be overridden by its subclasses.
The methods of the java.io.Writer class are same as the methods of the
java.io.OutputStream class.
All the methods of this class throw an IOException in case of errors.
The constructors for the Writer class are as follows:
Writer()
Writer(Object lock)
PrintWriter Class:
The PrintWriter class is a character-based class that is useful for console
output.
It implements all the print methods of the PrintStream class.
It does not have methods for writing raw bytes.
In such a case, a program uses unencoded byte streams.
50
Character Streams [3-4]
51
Character Streams [4-4]
The following Code Snippet displays the use of the PrintWriter class:
Code Snippet
. . .
InputStreamReader reader = new InputStreamReader (System.in);
OutputStreamWriter writer = new OutputStreamWriter (System.out);
PrintWriter pwObj = new PrintWriter (writer,true);
. . .
try
{
while (tmp != -1)
{
tmp = reader.read ();
ch = (char) tmp;
pw.println (“echo “ + ch);
}
}
catch (IOException e)
{
System.out.println (“IO error:” + e );
}
. . .
52
CharArrayReader Class
. . .
String temp = “Hello World”;
int size = temp.length();
char [] ch = new char[size];
temp.getChars(0, size, ch, 0);
CharArrayReader readObj = new CharArrayReader(ch, 0, 5);
53
CharArrayWriter Class [1-2]
54
CharArrayWriter Class [2-2]
. . .
CharArrayWriter fObj = new CharArrayWriter();
. . .
String temp = “Hello World”;
int size = temp.length();
char [] ch = new char[size];
temp.getChars(0, temp.length(), ch, 0);
fObj.write(ch);
char[] buffer = fObj.toCharArray();
System.out.println(buffer);
System.out.println(fObj.toString());
. . .
55
Chaining I/O Systems
56
Serialization
57
ObjectOutputStream Class [1-2]
58
ObjectOutputStream Class [2-2]
. . .
Point pointObj = new Point(50,75);
FileOutputStream fObj = new FileOutputStream(“point”);
ObjectOutputStream oos = new ObjectOutputStream(fObj);
oos.writeObject(pointObj);
oos.writeObject(new Date());
oos.close();
. . .
59
ObjectInputStream Class [1-5]
60
ObjectInputStream Class [2-5]
. . .
FileInputStream fObj = new FileInputStream(“point”);
ObjectInputStream ois = new ObjectInputStream(fObj);
Point obj = (Point) ois.readObject();
ois.close();
61
ObjectInputStream Class [3-5]
interface:
Code Snippet
import java.io.Serializable;
public class Employee implements Serializable{
String lastName;
String firstName;
double sal;
}
public class BranchEmpProcessor {
public static void main(String[] args) {
FileInputStream fIn = null;
FileOutputStream fOut = null;
ObjectInputStream oIn = null;
62
ObjectInputStream Class [4-5]
63
ObjectInputStream Class [5-5]
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
System.out.println(“finally”);
}
}
}
64
Summary
65