Java Streams, Files and
I/O
The java.io
package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output
destination. The stream in the java.io package supports many data such as
primitives, Object, localized characters, etc.
A stream can
be defined as a sequence of data.
The
InputStream is used to read data from a source and the OutputStream is used for
writing data to a destination.
Byte-oriented Streams
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 andFileOutputStream.
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.
InputStream
f = new FileInputStream("D:/Test.txt ");
or
File f = new
File("D:/Test.txt");
InputStream
f = new FileInputStream(f);
Methods
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 end of 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 end of 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.
OutputStream
f = new FileOutputStream("D:/Test.txt")
or
File f = new
File("D:/Test.txt ");
OutputStream
f = new FileOutputStream(f);
Methods
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 void write(int w)throws
IOException{}: This
methods writes the specified byte to the output stream.
4 public void write(byte[] w): Writes w.length bytes from the
mentioned byte array to the OutputStream.
Character-oriented Streams
File:
Java File
class represents the files and directory pathnames in an abstract manner. This
class is used for creation of files and directories, file searching, file
deletion etc.
Constructors
File(File
parent, String child);
File(String
pathname)
File(String
parent, String child)
File(URI
uri)
Methods
1 public String getName() Returns the name of the file or
directory denoted by this abstract pathname.
2 public String getParent() Returns the pathname string of this
abstract pathname's parent, or null if this pathname does not name a parent
directory.
3 public File getParentFile() Returns the abstract pathname of
this abstract pathname's parent, or null if this pathname does not name a
parent directory.
4 public String getPath() Converts this abstract pathname into
a pathname string.
5 public boolean isAbsolute() Tests whether this abstract pathname
is absolute. Returns true if this abstract pathname is absolute, false
otherwise
6 public String getAbsolutePath() Returns the absolute pathname string
of this abstract pathname.
7 public boolean canRead() Tests whether the application can
read the file denoted by this abstract pathname. Returns true if and only if
the file specified by this abstract pathname exists and can be read by the
application; false otherwise.
8 public boolean canWrite() Tests whether the application can
modify to the file denoted by this abstract pathname. Returns true if and only
if the file system actually contains a file denoted by this abstract pathname
and the application is allowed to write to the file; false otherwise.
9 public boolean exists() Tests whether the file or directory
denoted by this abstract pathname exists. Returns true if and only if the file
or directory denoted by this abstract pathname exists; false otherwise
10 public boolean isDirectory() Tests whether the file denoted by
this abstract pathname is a directory. Returns true if and only if the file
denoted by this abstract pathname exists and is a directory; false otherwise.
11 public boolean isFile() Tests whether the file denoted by
this abstract pathname is a normal file.
12 public long lastModified() Returns the time that the file
denoted by this abstract pathname was last modified. 13
13 public long length() Returns the length of the file
denoted by this abstract pathname. The return value is unspecified if this
pathname denotes a directory.
14 public boolean createNewFile() throws IOException Atomically
creates a new, empty file named by this abstract pathname if and only if a file
with this name does not yet exist. Returns true if the named file does not
exist and was successfully created; false if the named file already exists.
15 public boolean delete() Deletes the file or directory
denoted by this abstract pathname. If this pathname denotes a directory, then
the directory must be empty in order to be deleted. Returns true if and only if
the file or directory is successfully deleted; false otherwise.
16 public void deleteOnExit() Requests that the file or directory
denoted by this abstract pathname be deleted when the virtual machine
terminates.
17 public String[] list() Returns an array of strings naming
the files and directories in the directory denoted by this abstract pathname.
18 public String[] list(FilenameFilter
filter) Returns an
array of strings naming the files and directories in the directory denoted by
this abstract pathname that satisfy the specified filter.
20 public File[] listFiles() Returns an array of abstract
pathnames denoting the files in the directory denoted by this abstract
pathname.
21 public File[] listFiles(FileFilter
filter) Returns an
array of abstract pathnames denoting the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
22 public boolean mkdir() Creates the directory named by this
abstract pathname. Returns true if and only if the directory was created; false
otherwise.
23 public boolean mkdirs() Creates the directory named by this
abstract pathname, including any necessary but nonexistent parent directories.
Returns true if and only if the directory was created, along with all necessary
parent directories; false otherwise.
24 public boolean renameTo(File dest) Renames the file denoted by this
abstract pathname. Returns true if and only if the renaming succeeded; false
otherwise.
25 public boolean
setLastModified(long time) Sets the last-modified time of the file or directory named by this
abstract pathname. Returns true if and only if the operation succeeded; false
otherwise.
26 public boolean setReadOnly() Marks the file or directory named by
this abstract pathname so that only read operations are allowed. Returns true
if and only if the operation succeeded; false otherwise.
27 public static File
createTempFile(String prefix, String suffix, File directory) throws IOException Creates a new empty file in the
specified directory, using the given prefix and suffix strings to generate its
name. Returns an abstract pathname denoting a newly-created empty file.
28 public static File
createTempFile(String prefix, String suffix) throws IOException Creates an empty file in the default
temporary-file directory, using the given prefix and suffix to generate its
name. Invoking this method is equivalent to invoking createTempFile(prefix,
suffix, null). Returns abstract pathname denoting a newly-created empty file.
29 public int compareTo(File
pathname) Compares
two abstract pathnames lexicographically. Returns zero if the argument is equal
to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this
abstract pathname is lexicographically greater than the argument.
30 public int compareTo(Object o) Compares this abstract pathname to
another object. Returns zero if the argument is equal to this abstract
pathname, a value less than zero if this abstract pathname is lexicographically
less than the argument, or a value greater than zero if this abstract pathname
is lexicographically greater than the argument.
31 public boolean
equals(Object obj) Tests this abstract pathname for equality with the given
object. Returns true if and only if the argument is not null and is an abstract
pathname that denotes the same file or directory as this abstract pathname.
32 public String
toString() Returns the pathname string of this abstract pathname. This is
just the string returned by the getPath() method.
FileReader
This class inherits from the InputStreamReader class.
FileReader is used for reading streams of characters.
Constructors
FileReader(File file)
FileReader(FileDescriptor fd)
FileReader(String fileName)
Methods
1 public int read()
throws IOException Reads a single character. Returns an int, which
represents the character read.
2 public int
read(char [] c, int offset, int len) Reads characters into an array.
Returns the number of characters read. Example:
FileWriter
This class inherits from the OutputStreamWriter class. The
class is used for writing streams of characters.
Constructors
FileWriter(File file)
FileWriter(File file, boolean append)
FileWriter(FileDescriptor fd)
FileWriter(String fileName)
FileWriter(String fileName, boolean append)
Methods
1 public void
write(int c) throws IOException Writes a single character.
2 public void
write(char [] c, int offset, int len) Writes a portion of an array of
characters starting from offset and with a length of len.
3 public void
write(String s, int offset, int len) Write a portion of a String starting
from offset and with a length of len.
Serialization
and Deserialization
Java 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.
After a serialized object has been written into a file, it
can be read from the file and deserialized that is, the type information and
bytes that represent the object and its data can be used to recreate the object
in memory.
Most impressive is that the entire process is JVM
independent, meaning an object can be serialized on one platform and
deserialized on an entirely different platform.
Classes ObjectInputStream
and ObjectOutputStream are
high-level streams that contain the methods for serializing and deserializing
an object.
The ObjectOutputStream class contains many write methods for
writing various data types, but one method in particular stands out:
public final void
writeObject(Object x)throws IOException
The above method serializes an Object and sends it to the
output stream. Similarly, the ObjectInputStream class contains the following
method for deserializing an object:
public final Object
readObject()throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and
deserializes it. The return value is Object, so you will need to cast it to its
appropriate data type.
Notice that for a class to be serialized successfully, two
conditions must be met:
• The class must implement the java.io.Serializable
interface.
• All of the fields in the class must be serializable. If a
field is not serializable, it must be marked transient.
Example of serialization
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Employee e =new Employee();
e.name ="Raj"; e.address ="E/32";
e.city =”Delhi”;
try {
FileOutputStream fileOut =new
FileOutputStream("employee");
ObjectOutputStream out=new
ObjectOutputStream(fileOut); out.writeObject(e); out.close();
fileOut.close();
}
catch(IOException i) {
i.printStackTrace();
}
}
}
Example of deserialization
import java.io.*;
public class DeserializeDemo {
public static void main(String[]
args) {
Employee e
=null;
try {
FileInputStream fileIn =new
FileInputStream("employee.ser"); ObjectInputStream in=new
ObjectInputStream(fileIn);
e =(Employee)in.readObject();
in.close();
fileIn.close();
}
catch(IOException i) {
i.printStackTrace(); return;
}
catch(ClassNotFoundException c) {
System.out.println("Employee
class not found");
c.printStackTrace(); return;
}
System.out.println("Deserialized
Employee...");
System.out.println("Name:
"+ e.name);
System.out.println("Address:
"+ e.address);
System.out.println("Number: "+
e.city);
}
}
0 Comments