Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

File Handling in Java

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

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

We can perform file handling in java by Java I/O API.

Stream:

A stream is a sequence of data.  In Java a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and error message to the console.

1.   System.out.println("simple message");  

2.   System.err.println("error message");  

Let's see the code to get input from console.

1.   int i=System.in.read();//returns ASCII code of 1st character  

2.   System.out.println((char)i);//will print the character

 

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.

Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.

byte stream classification

There are two kinds of Streams −

·         InputStream − Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.

·        OutputStream − Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

java-io-flow.png

These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.

Some important Byte stream classes:

Stream class

Description

BufferedInputStream

Used for Buffered Input Stream.

BufferedOutputStream

Used for Buffered Output Stream.

DataInputStream

Contains method for reading java standard datatype

DataOutputStream

An output stream that contain method for writing java standard data type

FileInputStream

Input stream that reads from a file

FileOutputStream

Output stream that write to a file.

InputStream

Abstract class that describe stream input.

OutputStream

Abstract class that describe stream output.

PrintStream

Output Stream that contain print() and println() method

Useful methods of OutputStream:

Method

Description

1) public void write(int)throws IOException

is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException

is used to write an array of byte to the current output stream.

3) public void flush()throws IOException

flushes the current output stream.

4) public void close()throws IOException

is used to close the current output stream.

 

Example 1: write byte

1.   import java.io.FileOutputStream;  

2.   public class FileOutputStreamExample {  

3.       public static void main(String args[]){    

4.              try{    

5.                FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

6.                fout.write(65);    

7.                fout.close();    

8.                System.out.println("success...");    

9.               }catch(Exception e){System.out.println(e);}    

10.      }    

11.}  

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

A

Example 2: write string

1.   import java.io.FileOutputStream;  

2.   public class FileOutputStreamExample {  

3.       public static void main(String args[]){    

4.              try{    

5.                FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

6.                String s="Welcome to java";    

7.                byte b[]=s.getBytes();//converting string into byte array    

8.                fout.write(b);    

9.                fout.close();    

10.             System.out.println("success...");    

11.            }catch(Exception e){System.out.println(e);}    

12.      }    

13.}  

Output:

Success...

The content of a text file testout.txt is set with the data Welcome to java.

testout.txt

Welcome to java.

 

Useful methods of InputStream:

Method

Description

1) public abstract int read()throws IOException

reads the next byte of data from the input stream. It returns -1 at the end of file.

2) public int available()throws IOException

returns an estimate of the number of bytes that can be read from the current input stream.

3) public void close()throws IOException

is used to close the current input stream.

example 1: read single character

1.    import java.io.FileInputStream;  

2.    public class DataStreamExample {  

3.         public static void main(String args[]){    

4.              try{    

5.                FileInputStream fin=new FileInputStream("D:\\testout.txt");    

6.                int i=fin.read();  

7.                System.out.print((char)i);    

8.      

9.                fin.close();    

10.           }catch(Exception e){System.out.println(e);}    

11.          }    

12.         }  

Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content:

Welcome to java.

After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character.

Output:

W

example 2: read all characters

1.    package com.javatpoint;  

2.      

3.    import java.io.FileInputStream;  

4.    public class DataStreamExample {  

5.         public static void main(String args[]){    

6.              try{    

7.                FileInputStream fin=new FileInputStream("D:\\testout.txt");    

8.                int i=0;    

9.                while((i=fin.read())!=-1){    

10.              System.out.print((char)i);    

11.             }    

12.             fin.close();    

13.           }catch(Exception e){System.out.println(e);}    

14.          }    

15.         }  

Output:

Welcome to java.

 

Example 3 copy one file contents to other file:

import java.io.*;

public class CopyFile

{

          public static void main(String args[]) throws IOException

          { 

                   FileInputStream fis = new FileInputStream("d:/msg.txt");

                   FileOutputStream fos= new FileOutputStream("d:/output.txt");

                            int c;

                   while ((c = fis.read()) != -1)

                   {

                                      fos.write(c);

                   }

                   fis.close();

                   fos.close();                    

          }

}

Now let's have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt.

Java BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream:

1.    OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));  


Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:

1.    public class BufferedOutputStream extends FilterOutputStream  


Java BufferedOutputStream class constructors

Constructor

Description

BufferedOutputStream(OutputStream os)

It creates the new buffered output stream which is used for writing the data to the specified output stream.

BufferedOutputStream(OutputStream os, int size)

It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.

 

 

Java BufferedOutputStream class methods

Method

Description

void write(int b)

It writes the specified byte to the buffered output stream.

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

It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset

void flush()

It flushes the buffered output stream.

1.    //Example The flush() flushes the data of one stream and send it into another. 

2.    import java.io.*;  

3.    public class BufferedOutputStreamExample{    

4.    public static void main(String args[])throws Exception{    

5.         FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    

6.         BufferedOutputStream bout=new BufferedOutputStream(fout);    

7.         String s="Welcome to java.";    

8.         byte b[]=s.getBytes();    

9.         bout.write(b);    

10.      bout.flush();    

11.      bout.close();    

12.      fout.close();    

13.      System.out.println("success");    

14. }    

15. }  

Output:

Success

testout.txt

Welcome to java.

 

 

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

The important points about BufferedInputStream are:

  • When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
  • When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration

 

1.    public class BufferedInputStream extends FilterInputStream  


Java BufferedInputStream class constructors

Constructor

Description

BufferedInputStream(InputStream IS)

It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, int size)

It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

Java BufferedInputStream class methods

Method

Description

int available()

It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.

int read()

It read the next byte of data from the input stream.

int read(byte[] b, int off, int ln)

It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.

void close()

It closes the input stream and releases any of the system resources associated with the stream.

void reset()

It repositions the stream at a position the mark method was last called on this input stream.

void mark(int readlimit)

It sees the general contract of the mark method for the input stream.

long skip(long x)

It skips over and discards x bytes of data from the input stream.

boolean markSupported()

It tests for the input stream to support the mark and reset methods.

1.    import java.io.*;  

2.    public class BufferedInputStreamExample{    

3.     public static void main(String args[]){    

4.      try{    

5.        FileInputStream fin=new FileInputStream("D:\\testout.txt");    

6.        BufferedInputStream bin=new BufferedInputStream(fin);    

7.        int i;    

8.        while((i=bin.read())!=-1){    

9.         System.out.print((char)i);    

10.     }    

11.     bin.close();    

12.     fin.close();    

13.   }catch(Exception e){System.out.println(e);}    

14.  }    }  

Here, we are assuming that you have following data in "testout.txt" file:

java

Output:

java

Character Stream Classes

Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.

character stream classification

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.

PrintWriter

Output Stream that contain print() and println() method.

Reader

Abstract class that define character stream input

Writer

Abstract class that define character stream output

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.

Java FileReader Class

Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.

It is character-oriented class which is used for file handling in java.

Java FileReader class declaration

Let's see the declaration for Java.io.FileReader class:

1.    public class FileReader extends InputStreamReader  

Constructors of FileReader class

Constructor

Description

FileReader(String file)

It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

FileReader(File file)

It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

Methods of FileReader class

Method

Description

int read()

It is used to return a character in ASCII form. It returns -1 at the end of file.

void close()

It is used to close the FileReader class.

 

1.    import java.io.FileReader;  

2.    public class FileReaderExample {  

3.        public static void main(String args[])throws Exception{    

4.              FileReader fr=new FileReader("D:\\testout.txt");    

5.              int i;    

6.              while((i=fr.read())!=-1)    

7.              System.out.print((char)i);    

8.              fr.close();    

9.        }    }    

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to java.

Output:

Welcome to java.

 

Java FileWriter Class

Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.

Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.

Java FileWriter class declaration

Let's see the declaration for Java.io.FileWriter class:

1.    public class FileWriter extends OutputStreamWriter  

Constructors of FileWriter class

Constructor

Description

FileWriter(String file)

Creates a new file. It gets file name in string.

FileWriter(File file)

Creates a new file. It gets file name in File object.

Methods of FileWriter class

Method

Description

void write(String text)

It is used to write the string into FileWriter.

void write(char c)

It is used to write the char into FileWriter.

void write(char[] c)

It is used to write char array into FileWriter.

void flush()

It is used to flushes the data of FileWriter.

void close()

It is used to close the FileWriter.

1.    import java.io.FileWriter;  

2.    public class FileWriterExample {  

3.        public static void main(String args[]){    

4.             try{    

5.               FileWriter fw=new FileWriter("D:\\testout.txt");    

6.               fw.write("Welcome to java.");    

7.               fw.close();    

8.              }catch(Exception e){System.out.println(e);}    

9.              System.out.println("Success...");    

10.      }    

11. }  

Output:

Success...

testout.txt:

Welcome to java.

 

Java BufferedReader Class

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.

Java BufferedReader class declaration

Let's see the declaration for Java.io.BufferedReader class:

1.    public class BufferedReader extends Reader  


Java BufferedReader class constructors

Constructor

Description

BufferedReader(Reader rd)

It is used to create a buffered character input stream that uses the default size for an input buffer.

BufferedReader(Reader rd, int size)

It is used to create a buffered character input stream that uses the specified size for an input buffer.


Java BufferedReader class methods

Method

Description

int read()

It is used for reading a single character.

int read(char[] cbuf, int off, int len)

It is used for reading characters into a portion of an array.

boolean markSupported()

It is used to test the input stream support for the mark and reset method.

String readLine()

It is used for reading a line of text.

boolean ready()

It is used to test whether the input stream is ready to be read.

long skip(long n)

It is used for skipping the characters.

void reset()

It repositions the stream at a position the mark method was last called on this input stream.

void mark(int readAheadLimit)

It is used for marking the present position in a stream.

void close()

It closes the input stream and releases any of the system resources associated with the stream.

1.    import java.io.*;  

2.    public class BufferedReaderExample {  

3.        public static void main(String args[])throws Exception{    

4.              FileReader fr=new FileReader("D:\\testout.txt");    

5.              BufferedReader br=new BufferedReader(fr);    

6.              int i;    

7.              while((i=br.read())!=-1){  

8.              System.out.print((char)i);  

9.              }  

10.           br.close();    

11.           fr.close();    

12.     }    }    

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to javaTpoint.

Output:

Welcome to javaTpoint.

 

Reading data from console by InputStreamReader and BufferedReader

In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.

1.    import java.io.*;  

2.    public class BufferedReaderExample{    

3.    public static void main(String args[])throws Exception{             

4.        InputStreamReader r=new InputStreamReader(System.in);    

5.        BufferedReader br=new BufferedReader(r);            

6.        System.out.println("Enter your name");    

7.        String name=br.readLine();    

8.        System.out.println("Welcome "+name);    

9.    }    }  

Output:

Enter your name
SYCS 2017-18
Welcome SYCS 2017-18

 

Java File Class

The File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative.

The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.

Constructors

Constructor

Description

File(File parent, String child)

It creates a new File instance from a parent abstract pathname and a child pathname string.

File(String pathname)

It creates a new File instance by converting the given pathname string into an abstract pathname.

File(String parent, String child)

It creates a new File instance from a parent pathname string and a child pathname string.

File(URI uri)

It creates a new File instance by converting the given file: URI into an abstract pathname.

Useful Methods

Modifier and Type

Method

Description

static File

createTempFile(String prefix, String suffix)

It creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

boolean

createNewFile()

It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

boolean

canWrite()

It tests whether the application can modify the file denoted by this abstract pathname.String[]

boolean

canExecute()

It tests whether the application can execute the file denoted by this abstract pathname.

boolean

canRead()

It tests whether the application can read the file denoted by this abstract pathname.

boolean

isAbsolute()

It tests whether this abstract pathname is absolute.

boolean

isDirectory()

It tests whether the file denoted by this abstract pathname is a directory.

boolean

isFile()

It tests whether the file denoted by this abstract pathname is a normal file.

String

getName()

It returns the name of the file or directory denoted by this abstract pathname.

String

getParent()

It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Path

toPath()

It returns a java.nio.file.Path object constructed from the this abstract path.

URI

toURI()

It constructs a file: URI that represents this abstract pathname.

File[]

listFiles()

It returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname

long

getFreeSpace()

It returns the number of unallocated bytes in the partition named by this abstract path name.

String[]

list(FilenameFilter filter)

It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

boolean

mkdir()

It creates the directory named by this abstract pathname.

Example 1

1.    import java.io.*;  

2.    public class FileDemo {  

3.        public static void main(String[] args) {  

4.              try {  

5.                File file = new File("javaFile123.txt");  

6.                if (file.createNewFile()) {  

7.                    System.out.println("New File is created!");  

8.                } else {  

9.                    System.out.println("File already exists.");  

10.             }  

11.         } catch (IOException e) {  

12.             e.printStackTrace();  

13.         }  

14.     }  

15. }  

Example 2

1.    import java.io.*;  

2.    public class FileExample {  

3.    public static void main(String[] args) {  

4.        File f=new File("c:/My Documents");  

5.        String filenames[]=f.list();  

6.        for(String filename:filenames){  

7.            System.out.println(filename);  

8.        }  }  }  

Output:

"info.properties"
"info.properties".rtf
.DS_Store
.localized
Alok news
apache-tomcat-9.0.0.M19
apache-tomcat-9.0.0.M19.tar
bestreturn_org.rtf
BIODATA.pages
BIODATA.pdf
BIODATA.png
struts2jars.zip
workspace

Example 3

1.    import java.io.*;  

2.    public class FileExample {  

3.    public static void main(String[] args) {  

4.        File dir=new File("c:/My Documents");  

5.        File files[]=dir.listFiles();  

6.        for(File file:files){  

7.            System.out.println(file.getName()+" Can Write: "+file.canWrite()+"   

8.            Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");  

9.        }  }  }  

 

Directories in Java

A directory is a File which can contain a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories.

Creating Directories

There are two useful File utility methods, which can be used to create directories

·        The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.

·        The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates "/tmp/user/java/bin" directory −

Example

import java.io.File;
public class CreateDir {
   public static void main(String args[]) {
      String dirname = "e:/sycs1718/myfolder";
      File d = new File(dirname);
      // Create directory now.
      d.mkdirs();
   }
}

Note − Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Listing Directories

You can use list( ) method provided by File object to list down all the files and directories available in a directory as follows −

 

 

Example

import java.io.File;
public class ReadDir {
 
   public static void main(String[] args) {
      File file = null;
      String[] paths;
      try {      
         // create new file object
         file = new File("e:/sycs1718");
         // array of files and directory
         paths = file.list();
         // for each name in the path array
         for(String path:paths) {
            // prints filename and directory name
            System.out.println(path);
         }
      }catch(Exception e) {
         e.printStackTrace();
      }
   }
}

This will produce the following result based on the directories and files available in your e:/sycs1718/ directory −

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.

Serialization in java is a mechanism of writing the state of an object into a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization

Advantage of Java Serialization:

It is mainly used to travel object's state on the network (known as marshaling).

java-serialization.png

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.

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

 

 

Constructor

1) public ObjectOutputStream(OutputStream out) throws IOException {}

creates an ObjectOutputStream that writes to the specified OutputStream.

Important Methods

Method

Description

1) public final void writeObject(Object obj) throws IOException {}

writes the specified object to the ObjectOutputStream.

2) public void flush() throws IOException {}

flushes the current output stream.

3) public void close() throws IOException {}

closes the current output stream.

Example of Java Serialization

1.   import java.io.Serializable;  

2.   public class Student implements Serializable{  

3.    int id;  

4.    String name;  

5.    public Student(int id, String name) {  

6.     this.id = id;  

7.     this.name = name;  

8.    }  

9.   }  

In the above example, Student class implements Serializable interface. Now its objects can be converted into stream.

We are going to serialize the object of Student class. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.

1.   import java.io.*;  

2.   class Persist{  

3.    public static void main(String args[])throws Exception{  

4.     Student s1 =new Student(211,"ravi");    

5.     FileOutputStream fout=new FileOutputStream("e:/f.txt");  

6.     ObjectOutputStream out=new ObjectOutputStream(fout);  

7.     out.writeObject(s1);  

8.     out.flush();  

9.     System.out.println("success");  

10. }  

11.}  

success

Deserialization in java:

Deserialization is the process of reconstructing the object from the serialized state.It is the reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws IOException {}

creates an ObjectInputStream that reads from the specified InputStream.

Important Methods

Method

Description

1) public final Object readObject() throws IOException, ClassNotFoundException{}

reads an object from the input stream.

2) public void close() throws IOException {}

closes ObjectInputStream.

xample of Java Deserialization

1.   import java.io.*;  

2.   class Depersist{  

3.    public static void main(String args[])throws Exception{  

4.       

5.     ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  

6.     Student s=(Student)in.readObject();  

7.     System.out.println(s.id+" "+s.name);  

8.     

9.     in.close();  

10. }  

11.}  

211 ravi

Java Random Access Files

Using a random access file, we can read from a file as well as write to the file.

Reading and writing using the file input and output streams 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.

Random access files permit nonsequential, 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.

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.

"rws"

The file is opened in a read-write mode. Any modifications to the file's content and its metadata are written to the storage device immediately.

"rwd"

The file is opened in a read-write mode. Any modifications to the file's content are written to the storage device immediately.

Read and Write

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

RandomAccessFile  raf = new RandomAccessFile("randomtest.txt", "rw");

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.

The API consists of a few, easy to use, methods:

 

 

File Handling in Java File Handling in Java Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 13, 2022 Rating: 5

No comments:

Powered by Blogger.