Home Java Example Java Io Using a Random Access File in Java



Using a Random Access File in Java
Posted on: April 17, 2007 at 12:00 AM
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:

 

 

Related Tags for Using a Random Access File in Java:
javacfileidedomrandomiovireadintthisidpositionifieexamplewheretoexamposciwseilitdessectioncanusepefromceinmntososicaosiosjumpjadesspecdirallintoprodoctlxaxampsrectspdirectessatanyisirhallmpleaandccvausesssthavaccesshatpleplprndonomo


More Tutorials from this section

Ask Questions?    Discuss: Using a Random Access File in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.