0% found this document useful (0 votes)
20 views27 pages

2CS1010601 AdvJava - UNIT 2 Files

The document discusses file handling in Java, emphasizing the importance of permanent data storage and the use of the java.io package for input and output operations. It explains the concept of streams, classifying them into input and output streams, and details various classes for byte and character streams, including their methods. Additionally, it provides examples of reading from and writing to files using Java's file handling capabilities.

Uploaded by

naumanac1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views27 pages

2CS1010601 AdvJava - UNIT 2 Files

The document discusses file handling in Java, emphasizing the importance of permanent data storage and the use of the java.io package for input and output operations. It explains the concept of streams, classifying them into input and output streams, and details various classes for byte and character streams, including their methods. Additionally, it provides examples of reading from and writing to files using Java's file handling capabilities.

Uploaded by

naumanac1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Shri C. J.

Patel College of Computer Studies, Visnagar


2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Working with File Handling


✓ The input and output operation that we have performed so far were done
through screen and keyboard only.
✓ After the termination of program all the entered data is lost because primary
memory is volatile.
✓ If the data has to be used later, then it becomes necessary to keep it in
permanent storage device.
✓ Java provides the concept of file through which data can be stored on the disk or
secondary storage device.
✓ The stored data can be read whenever required.
✓ File is a collection of bytes stored in secondary storage device i.e. disk – thus, file
handling is used to read, write, append or update a file.
✓ Java I/O is used to process the input and produce the output.
✓ Java uses the concept of a stream to make I/O operation fast.
✓ The java.io package contains all the classes required for input and output
operations.
✓ Some of the common file handling operations are;
• Create file
• Read file
• Write file
• Change file permissions
• Delete file

Concept of Streams
✓ A stream is a path along which the data flows.
✓ Every stream has a source and a destination.
✓ We can build a complex file processing sequence using a series of simple stream
operations.
✓ A stream is a sequence of data.
✓ In Java, a stream is composed of bytes.
✓ Input refers to the flow of data into a program and output means the flow of data
out of a program.
✓ Input to a program may come from keyboard, mouse, memory, disk, network or
another program.

[ Page 1 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

✓ Output from program may go to the screen, printer, memory, disk, network or
another program.

Input Output

Relationship of Java program with I/O devices

✓ A stream presents a uniform, easy-to-use, object-oriented interface between the


program and the I/O devices.
✓ Java streams are classified into two basic types −
• InputStream − The InputStream reads data from the source (file) and sends
it to the program.
• OutputStream − The OutputStream takes data from the program and writes
it to the destination (file).

Using I/O Streams

[ Page 2 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Stream Classes
✓ The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data.
✓ These classes may be categorized into two groups based on the data type on
which they operate.

1. Byte stream classes provide support for managing I/O operations on


bytes.
2. Character stream classes provide support for managing I/O operations
on characters.

Classification of Java stream classes

[ Page 3 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Using the File Class


✓ Files and directories are accessed and manipulated by the File class.
✓ The File class represents the files and directory pathnames.
✓ This class is used for creation of files and directories, file searching, file deletion,
etc.
✓ The File object represents the actual file and directory on the disk.
✓ The File class contains several methods to rename, delete, and naming a file, to
work with the path name, deleting and renaming files, creating new directories,
listing the contents of a directory, and determining several common attributes of
files and directories.

Creation of File object


• A File object is created by passing a string with the name of a file – string that
represents the name of a file, or a String or another File object.

• For absolute path :


File a = new File("C:\\java\\HelloEx.java");
• For relative path,
File a = new File("HelloEx.java");

Creation of Files
✓ If we want to create and use a file, we need to decide the following about the file
and its intended purpose:
• Suitable name for the file.
• Data type to be stored.
• Purpose (reading, writing or updating).
• Method of creating the file.
✓ A file name is a unique string of characters that helps identify a file on the disk.
✓ The length of a file name and the characters allowed are dependent on the OS on
which the Java program is executed.
✓ A file name may contain two parts, a primary name and an optional period with
extension.
[ Page 4 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

✓ Example:
• input.data, salary, test.doc, student.txt, inventory, employee
✓ Data type is important to decide the type of file stream classes to be used for
handling the data like characters, bytes or primitive type.
✓ The purpose of using a file must also be decided before using it for reading only
or writing only or both the operations.
✓ A file stream can be defined using the classes of Reader/InputStream for
reading data and Writer/OutputStream for writing data.
✓ There are two ways of initializing the file stream objects.
✓ All of the constructors require that we provide the name of the file either
directly (as a literal string or variable) or indirectly by giving a file object that
has already been assigned a filename.

1. Direct approach
Example :
FileInputStream fis;
try
{ //assign the filename to the file stream object
fis = new FileInputStream(“test.dat”);
……………..
}
catch(IOException e)
{ …………….. }

2. Indirect approach
• The indirect approach uses a file object that has been initialized with the
desired filename.

Example :
File fname;
fname = new File(“test.dat”);
FileInputStream fis;
try
{ //give the value of the file object to the file stream object
fis = new FileInputStream(fname);
……………..
}
catch(IOException e)
{ …………….. }
[ Page 5 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Byte Streams Classes


✓ Byte stream classes are used to perform reading and writing of 8-bit bytes.
✓ Streams being unidirectional in nature can transfer bytes in one direction only,
that is, either reading data from the source into a program or writing data from a
program to the destination.
✓ Java provides two types of byte stream classes:
1. InputStream classes
2. OutputStream classes

InputStream Classes
• Input stream classes are used to read 8-bit bytes from the stream.
• The InputStream class is the super class for all byte-oriented input stream
classes.
• All the methods of this class throw an IOException.
• The InputStream class is an abstract class, and therefore, we cannot create
instances of this class.
• We must use the subclasses that inherit from this class.

• InputStream and FilterInputStream are abstract classes.


[ Page 6 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

InputStream Classes
1. BufferedInputStream
▪ Contains methods to read bytes from the buffer (memory area).

2. ByteArrayInputStream
▪ Contains methods to read bytes from a byte array.
3. DataInputStream
▪ Contains methods to read Java primitive data types.
4. FileInputStream
▪ Contains methods to read bytes from a file.
5. FilterInputStream
▪ Contains methods to read bytes from other input streams which it uses as its
basic source of data.

6. ObjectInputStream
▪ Contains methods to read objects.
7. PipedInputStream
▪ Contains methods to read from a piped output stream. A piped input stream
must be connected to a piped output stream.

8. SequenceInputStream
▪ Contains methods to concatenate multiple input streams and then read from
the combined stream.

• The InputStream class defines various methods to perform reading operations


on data of an input stream.

[ Page 7 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Methods of InputStream Class


1. int read()
▪ Reads a byte from the input stream. It returns -1 when end of file is
encountered.

2. int read (byte b[])


▪ Reads an array of bytes into b. It returns -1 when end of file is encountered.

3. int read (byte b[], int n, int m)


▪ Reads m bytes into b starting from nth byte.
▪ It returns -1 when end of file is encountered.
4. int available ()
▪ Returns the number of bytes available in the I/P stream.
5. void mark(int nBytes)
▪ Marks the current position in the input stream until 'nBytes' bytes are read.
6. void reset ()
▪ Resets the input pointer to the beginning of the stream.
7. long skip (long nBytes)
▪ Skips 'nBytes' bytes from the input stream and returns the number of actually
skipped byte.

8. void close ()
▪ Closes the input stream.
• Note : the class DataInputStream extends FilterInputStream and
implements the interface DataInput. Therefore, the DataInputStream class
implements the methods described in DataInput in addition to using the
methods of InputStream class.
• The DataInput interface contains the following methods:

• readshort() • readDouble()
• readInt() • readLine()
• readLong() • readChar()
• readFloat() • readBoolean()
[ Page 8 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

OutputStream Classes
• Java's output stream classes are used to write 8-bit bytes to a stream.
• The OutputStream class is the super class for all byte-oriented output stream
classes.
• OutputStream class is an abstract class.
• An output stream accepts output bytes and sends them to some link.
• All the methods of this class throw an IOException.
• Being an abstract class, the OutputStream class cannot be instantiated.
• The several subclasses of the OutputStream can be used for performing the
output operations.

• OutputStream and FilterOutputStream are abstract classes.

OutputStream Classes
1. BufferedOutputStream
▪ Contains methods to write bytes into the buffer.

[ Page 9 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

2. ByteArrayOutputStream
▪ Contains methods to write bytes into a byte array.
3. DataOutputStream
▪ Contains methods to write Java primitive data types.
4. FileOutputStream
▪ Contains methods to write bytes to a file.
5. FilterOutputStream
▪ Contains methods to write to other output streams.
6. ObjectOutputStream
▪ Contains methods to write objects.
7. PipedOutputStream
▪ Contains methods to write to a piped output stream.
8. PrintStream
▪ Contains methods to print Java primitive data types.
• The OutputStream class defines methods to perform writing operations.

Methods of OutputStream Class


1. void write (int i)
▪ Writes a single byte to the output stream.
2. void write (byte b[] )
▪ Writes all bytes in the array b to the output stream.
3. void write(bytes b[],int n, int m)
▪ Writes m bytes from array b starting from nth byte.
4. void flush ()
▪ Flushes the output stream and writes the waiting buffered output bytes.
[ Page 10 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

5. void close ()
▪ Closes the output stream.
• Note: the class DataOutputStream extends FilterOutputStream and
implements the interface DataOutput. Therefore, the DataOutputStream
class implements the methods described in DataOutput in addition to using
the methods of OutputStream class.
• The DataOutput interface contains the following methods:
• writeshort() • writeDouble()
• writeInt() • writeLine()
• writeLong() • writeChar()
• writeFloat() • writeBoolean()

Example : To write and read bytes from a file


import java.io.*;
class WRByte
{
public static void main(String s[ ])
{
byte sub[] = {'J','a','v','a','\n','.','N','E','T','\n','D','W','M'};
try
{
FileOutputStream fos = new FileOutputStream("sub.txt");
fos.write(sub);
System.out.println("Data written to the file successfully");
fos.close();
FileInputStream fis = new FileInputStream("sub.txt");
int b;
while(( b = fis.read() ) != -1)
{
System.out.print((char)b);
}
fis.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}
[ Page 11 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Example : To copy bytes from one file to another file


import java.io.*;
class CopyByte
{
public static void main(String s[])
{
int b;
try
{
FileInputStream fis = new FileInputStream("sub.txt");
FileOutputStream fos = new FileOutputStream("subcopy.txt");
while((b=fis.read())!= -1)
{
fos.write(b);
}
System.out.println("Data copy to the file successfully");
fis.close();
fos.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

[ Page 12 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Character Streams Classes


✓ Java Character streams can be used to read and write 16-bit characters.
✓ There are two types of character stream classes :
1. FileReader Class
2. FileWriter Class
✓ Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.

Reader Stream Classes


• Reader classes are used to read 16-bit unicode characters from the file (input
stream).
• The Reader class is the super class for all character-oriented input stream
classes.
• All the methods of this class throw an IOException.
• Being an abstract class, the Reader class cannot be instantiated hence its
subclasses are used.

[ Page 13 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Reader Classes
1. BufferedReader
▪ Contains methods to read characters from the buffer.
2. CharArrayReader
▪ Contains methods to read characters from a character array.
3. FileReader
▪ Contains methods to read from a file.
4. FilterReader
▪ Contains methods to read from underlying character-input stream.
5. InputStreamReader
Contains methods to convert bytes to characters.

6. PipeReader
▪ Contains methods to read from the connected piped output stream.
7. StringReader
▪ contains methods to read from a string
• The Reader class defines various methods to perform reading operations on
data of an input stream.
• The Reader class contains methods that are identical to those available in the
InputStream class.

[ Page 14 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Methods of Reader Class


1. int read()
▪ Reads a byte from the input stream. It returns -1 when end of file is
encountered.

2. int read (char ch[])


▪ Reads an array of characters into ch. It returns -1 when end of file is
encountered.

3. int read (char ch[], int n, int m)


▪ Reads m characters into ch starting from nth byte. It returns -1 when end of
file is encountered.

4. void mark(int nChars)


▪ marks the current position in the input stream until 'nChars' characters are
read.

5. void reset ()
▪ Resets the input pointer to the beginning of the stream.
6. long skip (long nChars)
▪ skips 'nChars' characters from the input stream and returns the number of
actually skipped characters.

7. void close ()
▪ Closes the input stream.

[ Page 15 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Writer Stream Classes


• Writer classes are used to write 16-bit Unicode characters on files.
• The Writer class is the super class for all character-oriented output stream
classes.
• All the methods of this class throw an IOException.
• Being an abstract class, the Writer class cannot be instantiated hence, its
subclasses are used. Some of these are listed in Table.

Writer Classes

1. BufferedWriter
▪ Contains methods to write characters to a buffer.
2. FileWriter
▪ Contains methods to write to a file.
3. FilterWriter
▪ Contains methods to write characters to underlying output stream.

[ Page 16 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

4. CharArrayWriter
▪ Contains methods to write characters to a character array.
5. OutputStreamWriter
▪ Contains methods to convert from bytes to character.
6. PipedWriter
▪ Contains methods to write to the connected piped input stream.
7. StringWriter
▪ Contains methods to write to a string.
• The Writer class defines various methods to perform writing operations on
output stream.

Methods of Writer Class


1. void write ( ) :
▪ Writes data to the output stream.

2. void write (int i)


▪ Writes a single character to the output stream.
3. void write (char ch[] )
▪ Writes all characters in the array ch to the output stream.
4. void write(char ch [], int n, int m)
▪ Writes m characters from array ch starting from nth character.
5. void close ( ) :
▪ Closes the output stream.
6. void flush () :
▪ Flushes the output stream and writes the waiting buffered output characters.

[ Page 17 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Example : To write and read characters from a file


import java.io.*;
class WRChar
{
public static void main(String s[])
{
try
{
FileWriter fw = new FileWriter("city.txt");
fw.write("Visnagar \n");
fw.write("Mahesana \n");
fw.write("Patan");
System.out.println("Data written to the file successfully");
fw.close();
int x;
FileReader fr = new FileReader("city.txt");
while((x=fr.read())!=-1)
{
System.out.print((char)x);
}
fr.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

Example : To copy characters from one file into another file


import java.io.*;
class CopyChar
{
public static void main(String s[])
{
try
{
FileReader fr = new FileReader("city.txt");
FileWriter fw = new FileWriter("citycopy.txt");
int x;

[ Page 18 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

while((x=fr.read())!=-1)
{
fw.write(x);
}
System.out.println("Data cpoy to the file successfully");
fw.close();
fr.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

[ Page 19 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Input / Output Exceptions


✓ When creating files and performing I/O operations on them, the system may
generate I/O related exceptions.

• Important I/O Exceptions Classes and their Functions

1. EOFException
• Signals that an end of the file or end of stream has been reached
unexpectedly during input.

2. FileNotFoundException
• Informs that a file could not be found.
3. InterruptedException
• Warns that an I/O operation has been interrupted.
4. IOException
• Signals that an O/P exception of some sort has occurred.
✓ Each I/O statement must have an exception handler around it as shown below or
the method must declare that it throw an IOException.

try
{
…………..
}
catch(IOException e)
{
…………..
}

[ Page 20 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Handling Primitive Data Types


✓ The basic input and output streams provide read/write methods that can be
used for reading/writing bytes or characters.
✓ If we want to read/write the primitive data types such as integers and doubles,
we can use filter classes as wrappers on the existing I/O streams to filter data to
the original stream.
✓ The two filter classes supported for creating “data streams” for primitive data
types are:

[1] DataInputStream [2] DataOutputStream

DataInputStream Creation
1. Create Input File Stream:
• Example : FileInputStream fis = new FileInputStream(infile);
2. Create Input Data Stream:
• Example : DataInputStream dis = new DataInputStream( fis );
▪ The first statement creates the file input stream (fis).
▪ The second statement creates the data input stream (dis).
▪ These statements wrap dis on fis and use it as a “filter”.
▪ Note : the file object infile must be initialized with the appropriate file name
before it is used. We may also use file name directly in place of file object.

[ Page 21 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

❖ Methods Supported:
• readBoolean(), readByte(), readChar(), readShort(), readInt(), readLong(),
readFloat(), readDouble()
• They read data stored in file in binary format.

Data Output Stream Creation

1. Create Output File Stream


• Example : FileOutputStream fos = new FileOutputStream(outfile);
2. Create Output Data Stream:
• Example : DataOutputStream dos = new DataOutputStream( fos );
▪ The first statement creates the file output stream (fos).
▪ The second statement creates the data output stream (dos).
▪ These statements wrap dos on fos and use it as a “filter”.
▪ Note : the file object outfile must be initialized with the appropriate file
name before it is used. We may also use file name directly in place of file
object.

❖ Methods Supported :
• writeBoolean(), writeByte(), writeChar(), writeShort(), writeInt(),
writeLong(), writeFloat(), writeDouble() They write data to file in binary
format.

Example : To read and write primitive data


import java.io.*;
class Primitive
{
public static void main(String s[])
{
try
{
FileOutputStream fos = new FileOutputStream("data.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(5432);
dos.writeDouble(1234.567);
dos.writeBoolean(true);
dos.writeChar('C');
[ Page 22 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

dos.close();
fos.close();
FileInputStream fis = new FileInputStream("data.txt");
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
catch(Exception e)
{ System.out.println("Exception : " + e); }
}
}

Example : To store and retrieve integers using single file


import java.io.*;
class IntFile
{
public static void main(String s[ ])
{
try
{
FileOutputStream fos = new FileOutputStream("Integers.txt");
DataOutputStream dos = new DataOutputStream(fos);
for(int no=1; no<=5; no++)
dos.writeInt(no*10);
System.out.println("Integers written to the file");
dos.close();
FileInputStream fis = new FileInputStream("Integers.txt");
DataInputStream dis = new DataInputStream(fis);
for(int no=1; no<=5; no++)
System.out.println(dis.readInt());
dis.close();
}
catch(Exception e)
{ System.out.println("Exception : " + e); }
}
}

[ Page 23 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Random Access Files


✓ Java.io.RandomAccessFile Class provides a way to random access files using
reading and writing operations. It works like an array of byte storted in the File.
✓ Random access files permit non sequential, or random, access to a file's
contents.
✓ To access a file randomly, you open the file, seek a particular location, and read
from or write to that file.
✓ Using a random access file, we can read from a file as well as write to the file.
✓ Reading and writing using the FileInputstream and FileOutpueStream are a
sequential process.
✓ Using a random access file, we can read or write at any position within the file.
✓ An object of the RandomAccessFile class can do the random file access. We can
read/write bytes and all primitive types values to a file.

❖ Declaratioon :

public class RandomAccessFile extends Object implements


DataOutput, DataInput, Closeable

❖ 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.

[ Page 24 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

Constructors
• We create an instance of the RandomAccessFile class by specifying the file
name and the access mode.

1. RandomAccessFile(File file, String mode)


• Creates a random access file stream to read from, and optionally to write
to, the file specified by the File argument.

2. RandomAccessFile(String name, String mode)


• Creates a random access file stream to read from, and optionally to write
to, a file with the specified name.
• mode - the access mode
Example :
RandomAccessFile r = new RandomAccessFile("test.txt", "rw");

Methods
1. void close()
• Closes this random access file stream and releases any system resources
associated with the stream.

2. long length() : Returns the length of file.


3. int read() : Reads a byte of data from file.
4. int read(byte[] b)
• Reads up to b.length bytes of data from file into an array of bytes.

5. int read(byte[] b, int off, int len)


• Reads up to len bytes of data from file into an array of bytes.

6. boolean readBoolean() : Reads a boolean from file.

[ Page 25 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

7. byte readByte() : Reads a signed eight-bit value from file.


8. char readChar() : Reads a character from file.
9. double readDouble() : Reads a double from file.
10. float readFloat() : Reads a float from this file.
11. void readFully(byte[] b , int off , int len)
• Reads exactly len bytes from this file into the byte array, starting at the
current file pointer.
12. int readInt() : Reads a signed 32-bit integer from file.
13. String readLine() : Reads the next line of text from file.
14. long readLong(): Reads a signed 64-bit integer from file.
15. short readShort(): Reads a signed 16-bit number from file.
16. void seek(long pos)
• Sets the file-pointer offset, measured from the beginning of file, at which the
next read or write occurs.

17. void setLength(long newLength) : Sets the length of file.


18. int skipBytes(int n)
• Skips over n bytes of input discarding the skipped bytes.

19. void write(byte[] b)


• Writes b.length bytes from the specified byte array to file, starting at the
current file pointer.

20. void write(byte[] b , int off , int len)


• Writes len bytes from the specified byte array starting at offset off to file.

21. void write(int b) : Writes the specified byte to file.


22. void writeBoolean(boolean v) : Writes a boolean to the file.
23. void writeByte(int v) : Writes a byte to the file.
24. void writeBytes(String s) :Writes the string to the file.
25. void writeChar(int v) : Writes a char to the file.
[ Page 26 of 27 ]
Shri C. J. Patel College of Computer Studies, Visnagar
2CS1010601 : Building Application Using Advance Java
[ UNIT – II : Managing Input /Output Files in Java ]

26. void writeChars(String s) : Writes a string to the file.


27. void writeDouble(double v) : Writes double value to the file.
28. void writeFloat(float v) : Writes float value to the file.
29. void writeInt(int v) : Writes int value to the file.
30. void writeLong(long v) : Writes long value to the file.
31. void writeShort(int v) : Writes short value to the file.

Example : To write and read data using random access file


import java.io.*;
class RandomFile
{
public static void main(String s[])
{
try
{
RandomAccessFile file = new RandomAccessFile("raccess.txt","rw");
file.writeChar('C');
file.writeInt(12345);
file.writeDouble(1234.567);
file.seek(0);
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2);
System.out.println(file.readInt());
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

[ Page 27 of 27 ]

You might also like