Search code examples
javalines-of-codeblock-comments

how to count the loc without block comments?


I am trying to get the number of lines of code from a java file. But I am having trouble counting them.

First I tried to skip them with ifs, but my idea does not work. Now I am counting the same lines with comments, my Java file has this header. Any ideas, I am stuck in how to count them.

My if is for getting the number of lines with the comments block. I trying to make a subtract.

/*
example
example
*/

int totalLoc = 0;
int difference = 0;
while((line =buff.readLine()) !=null){

    if((line.trim().length() !=0 &&(!line.contains("/*") ||!line.contains("*/")) )){
       if(line.startsWith("/*")){
           difference++;
       }else if(linea.startsWith("*/")){
           difference++;
       }else{
           difference++;
       }
    }
}

Solution

  • If you want to count lines in any file write below method and pass the fileName as input to below method and it will return counts.

    public int count(String filename) throws IOException
         {
            InputStream is = new BufferedInputStream(new FileInputStream(filename));
            try
            {
                byte[] c = new byte[1024];
                int count = 0;
                int readChars = 0;
                boolean empty = true;
                while ((readChars = is.read(c)) != -1)
                {
                    empty = false;
                    for (int i = 0; i < readChars; ++i)
                    {
                        if (c[i] == '\n')
                            ++count;
                    }
                }
                return (count == 0 && !empty) ? 1 : count;
            }
            finally
            {
                is.close();
            }
        }