Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



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

Related Tutorials


 
 

Share on Google+Share on Google+

Using a Random Access File in Java

Advertisement
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:

 

 

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 17, 2007

Related Tutorials

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

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Austin
July 27, 2012
Small error, confusing in-code comment

In the comment above the call to the RandomAccessFile constructor, it says that it opens the file for both reading and writing. That confused me because the call to the constructor only had "r" in the second argument instead of "rw". I just recently learned about random access files, so that's why i found it so confusing. Anyway, I just wanted to point it out so no one else who is fairly new to java gets confused.
DMCA.com