Wednesday, 30 November 2016

Implement a program to count number of lines and words in the file

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. RandomAccessFile can work with strings using its readUTF() and writeUTF() methods.
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. 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. To read data from random file use read( ) method and to write data into random file use write( ) method.

The following program reads the file contents using RandomAccessFile and count the number of words and line. 


class PerformTask
 void task()
  char c;
  int words=1,lines=1,chars=0;
   RandomAccessFile ff = new RandomAccessFile("test.txt","r");
    c = (char);
    if(c ==' ')
    else if(c=='\n')
   System.out.println("Words = "+words+" lines = "+lines);
  catch(IOException ie){}
 public static void main(String args[])
  PerformTask p = new PerformTask();
C:\>java PerformTask
Words = 7 lines = 3

No comments:

Post a Comment