Java File Handling
Java File Handling
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code understand
the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
These two abstract classes have several concrete classes that handle various devices such as disk
files, network connection etc.
These two abstract classes have several concrete classes that handle unicode character.
Some important Charcter stream classes.
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
Output Stream that contain print() and println()
PrintWriter
method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException
Mode
A random access file can be created in four different access modes. The access mode value is a
string. They are listed as follows:
Mode Meaning
"r" The file is opened in a read-only mode.
"rw" The file is opened in a read-write mode. The file is created if it does not exist.
The file is opened in a read-write mode. Any modifications to the file's content and its
"rws"
metadata are written to the storage device immediately.
The file is opened in a read-write mode. Any modifications to the file's content are written
"rwd"
to the storage device immediately.
A random access file has a file pointer that moves forward when we read data from it or write data
to it.
The file pointer is a cursor where our next read or write will start.
Its value indicates the distance of the cursor from the beginning of the file in bytes.
We can get the value of file pointer by using its getFilePointer() method.
When we create an object of the RandomAccessFile class, the file pointer is set to zero.
We can set the file pointer at a specific location in the file using the seek() method.
The length() method of a RandomAccessFile returns the current length of the file. We can extend or
truncate a file by using its setLength() method.
Example
The following code shows how to read and write Files Using a RandomAccessFile Object.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
// w ww .j av a 2s. c om
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "randomaccessfile.txt";
File fileObject = new File(fileName);
if (!fileObject.exists()) {
initialWrite(fileName);
}
readFile(fileName);
readFile(fileName);
}
System.out.println(counter);
System.out.println(msg);
incrementReadCounter(raf);
raf.close();
}
Class declaration
Following is the declaration for Java.io.RandomAccessFile class:
public class RandomAccessFile
extends Object
implements DataOutput, DataInput, Closeable
Class constructors
S.N. Constructor & Description
Class methods
S.N. Method & Description
1 void close()
This method Closes this random access file stream and releases any system resources
associated with the stream.
2 FileChannel getChannel()
This method returns the unique FileChannel object associated with this file.
3 FileDescriptor getFD()
This method returns the opaque file descriptor object associated with this stream.
4 long getFilePointer()
This method returns the current offset in this file.
5 long length()
This method returns the length of this file.
6 int read()
This method reads a byte of data from this file.
7 int read(byte[] b)
This method reads up to b.length bytes of data from this file into an array of bytes.
8 int read(byte[] b, int off, int len)
This method reads up to len bytes of data from this file into an array of bytes.
9 boolean readBoolean()
This method reads a boolean from this file.
10 byte readByte()
This method reads a signed eight-bit value from this file.
11 char readChar()
This method reads a character from this file.
12 double readDouble()
This method reads a double from this file.
13 float readFloat()
This method reads a float from this file.
14 void readFully(byte[] b)
This method reads b.length bytes from this file into the byte array, starting at the
current file pointer.
16 int readInt()
This method reads a signed 32-bit integer from this file.
17 String readLine()
This method reads the next line of text from this file.
18 long readLong()
This method reads a signed 64-bit integer from this file.
19 short readShort()
This method reads a signed 16-bit number from this file.
20 int readUnsignedByte()
This method reads an unsigned eight-bit number from this file.
21 int readUnsignedShort()
This method reads an unsigned 16-bit number from this file.
22 String readUTF()
This method reads in a string from this file.
25 int skipBytes(int n)
This method attempts to skip over n bytes of input discarding the skipped bytes.
26 void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file, starting at
the current file pointer.
28 void write(int b)
This method writes the specified byte to this file.
29 void writeBoolean(boolean v)
This method writes a boolean to the file as a one-byte value.
30 void writeByte(int v)
This method writes a byte to the file as a one-byte value.
31 void writeBytes(String s)
This method writes the string to the file as a sequence of bytes.
32 void writeChar(int v)
This method writes a char to the file as a two-byte value, high byte first.
33 void writeChars(String s)
This method writes a string to the file as a sequence of characters.
34 void writeDouble(double v)
This method converts the double argument to a long using the doubleToLongBits
method in class Double, and then writes that long value to the file as an eight-byte
quantity, high byte first.
35 void writeFloat(float v)
This method converts the float argument to an int using the floatToIntBits method in
class Float, and then writes that int value to the file as a four-byte quantity, high byte
first.
36 void writeInt(int v)
This method writes an int to the file as four bytes, high byte first.
37 void writeLong(long v)
This method writes a long to the file as eight bytes, high byte first.
38 void writeShort(int v)
This method writes a short to the file as two bytes, high byte first.
39 void writeUTF(String str)
This method writes a string to the file using modified UTF-8 encoding in a machine-
independent manner.
import java.io.IOException;
import java.io.RandomAccessFile;
private static void writeData(String filePath, String data, int seek) throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(seek);
file.write(data.getBytes());
file.close();
}
private static byte[] readCharsFromFile(String filePath, int seek, int chars) throws
IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(seek);
byte[] bytes = new byte[chars];
file.read(bytes);
file.close();
return bytes;
}
}
Copy content of one file to another
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
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.
To demonstrate how serialization works in Java, I am going to use the Employee class that we
discussed early on in the book. Suppose that we have the following Employee class, which
implements the Serializable interface −
Example
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
Notice that for a class to be serialized successfully, two conditions must be met −
All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check the documentation
for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable;
otherwise, it's not.
Serializing an Object
The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.
When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.
Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser
extension.
Example
import java.io.*;
public class SerializeDemo {
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i) {
i.printStackTrace();
}
}
}
Deserializing an Object
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program. Study the program and try to determine its output −
Example
import java.io.*;
public class DeserializeDemo {
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
The value of the SSN field was 11122333 when the object was serialized, but because the
field is transient, this value was not sent to the output stream. The SSN field of the
deserialized Employee object is 0.
Multithreaded server
Following example demonstrates how to create a multithreaded server by using
ssock.accept() method of Socket class and MultiThreadServer(socketname) method of
ServerSocket class.
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
Result:
The above code sample will produce the following result.
Listening
Connected