Saturday 8 February 2014

Program to read code from a file and print it to the console ignoring the comments in it.

This question was asked to me in Java Interview in Rolta India Pvt. Ltd. I  want to share the logic and code with you.

The solution is simple.

  • Create a Java Application (say IO)
  • Create a file with name code.java in your application folder. Place it in the root folder of your application. Your folder structure will look like this. To find the location of root folder of your application right click your project in Eclipse, Select Properties,  Select Resources from the left pane of the windows that opens. Check the value of Location property that is where your application root is.











  • Create a class (say Main)
  • Copy paste the following code in it.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {

 public static void main(String[] args) {
  try {
   File file = new File("code.java");
   FileReader fileReader = new FileReader(file);

   // Print the file or count the number of characters
   int data = fileReader.read();
   int count = 0;
   while (data != -1) {
    count++;
    // System.out.print((char)data);
    data = fileReader.read();
   }
  
   char[] cbuf = new char[count];
   fileReader.close();
   // initialize fileReader to start of file
   fileReader = new FileReader(file);
   fileReader.read(cbuf);

   for (int i = 0; i < count; i++) {
    if (cbuf[i] == '/') {
     if (cbuf[i + 1] == '*') {// check for multiline comments
      i += 2;
      while (!(cbuf[i] == '*' && cbuf[i + 1] == '/')) {
       i++; // ignore
      }
      i += 2;// ignore */
     }

     if (cbuf[i + 1] == '/') {// check for single line comments
      i += 2;
      while (cbuf[i] != '\n') {
       i++;
      }// while
     }
    }// check for multiline comments

    // print
    System.out.print(cbuf[i]);
   }// for
   fileReader.close();
  } catch (FileNotFoundException e) {
   System.out.println(e.getMessage());
  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
  /*
   * some 
   * multiline comments
   */
 }
}

  • Copy the same code in code.java file in root folder of your application. Save it.
  • This program will print the code in code.java while ignoring the comments.
  • Run the program. 
  • In our class we created a file object. Then wrapped a FileReader around it. Note that as we are working with characters we have used FileReader.
  • We need to create a char array into which we can read the contents of the file. But in java to initialize an array you need to know the size.
  • So we have used a while loop to count the number of characters in the file. Then we can use that info to initialize our char array.
  • The public int read() method of FileReader class returns -1 if end of file is reached else returns the data at current pointer position and advances the data to next character. After executing the below loop our pointer will be at the end of file. 

                        int count = 0;
   while (data != -1) {
    count++;
    // System.out.print((char)data);
    data = fileReader.read();
   }

  • To make things simple we can also use the public int length() method of the File class to give us the number of characters in it.
                          int count = file.length();
  • We used the public int read(char[] cbuf)  method to read the contents of the file into that char array cbuf. In the while loop above we traversed the entire file from start to end to count the number of characters. So we have re-initialized it to start of the file.
  • The for loop contains the logic to skip multiline and single line comments.
  • If encounter '/' we check if the next character is '*' ,if it is then we go on ignoring the file until we find '*' immediately followed by '/'.
  • If we encounter '/' we check if the next character is '/', if it is then we go in ignoring the entire line.
  • If find neither a single line nor a multiline comment we print the chaaracters of the array 1 by 1.
Thats it. Hope this helps. 
Signing off!!!!
Happy Learning :)