Using a Random Access File in Java

Ads
 

Using a Random Access File in Java

In this section, you will learn the Random Access File features provided by java io package.

In this section, you will learn the Random Access File features provided by java io package.
C:\nisha>javac RandAccessFile.java

C:\nisha>java RandAccessFile
Enter File name : Filterfile.txt
Write Successfully

Download this example.

The another program reads the characters from a file using the readByte( ) method.

import java.io.*;

public class ReadAccessFile{
  public static void main(String[] argsthrows IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter File name : ");
  String str = in.readLine();
  File file = new File(str);
  if(!file.exists())
  {
  System.out.println("File does not exist.");
  System.exit(0);
  }
  try{
  //Open the file for both reading and writing
  RandomAccessFile rand = new RandomAccessFile(file,"r")
  int i=(int)rand.length();
  System.out.println("Length: " + i);
 rand.seek(0);  //Seek to start point of file
  for(int ct = 0; ct < i; ct++){
  byte b = rand.readByte(); //read byte from the file
  System.out.print((char)b)//convert byte into char
  }
  rand.close();
  }
  catch(IOException e)
  {
  System.out.println(e.getMessage());
  }
  }
}

Output of the Program:

C:\nisha>java ReadAccessFile
Enter File name : Filterfile.txt
Length: 30
??t h i s i s a f i l e
C:\nisha>

Download this Program:

 

 

Ads

Ads