Java文件中会有两种注释方式:// /*...*/
所以代码要能去除以上两种注释风格的代码,同时不能包含空行...
具体代码实现如下:
/** * @author wuwh
* @return result=codeLineNumber of javaFile
* @Param javaFile is target file need stating.
*/
public static int statCodeLineNumber(File javaFile) throws IOException
{
int result = 0;
//transfer javaFile to java stream...
FileReader fileR = new FileReader(javaFile);
BufferedReader br = new BufferedReader(fileR);
String str;
Stack<String> codeStack = new Stack<String>();
//read javaFile line by line util the end...
while((str = br.readLine())!=null)
{
if (!str.trim().startsWith("//")) {
if (!str.trim().startsWith("/*")) {
//ensure if current line is empty line...
if (str.trim().length()!=0) {
result++;
}
else {
System.out.println("one empty line appeared...");
}
}
else {
codeStack.push(str);
System.out.println("after/* "+str);
//if codeStack isn't empty, then there must be--
//at least one String ending with "/*" at the bottom of codeStack.
//so needs looping
while(!codeStack.isEmpty())
{
//current string doesn't endWith "*/" after trim operation
while(((str=br.readLine())!=null)&&
(!(str.trim()).endsWith("*/")))
{
codeStack.push(str);
System.out.println("after/* "+str);
}
//pop the element of codeStack util current string startsWith "/*"
String topStringOfStack;
while((!codeStack.isEmpty())&&
(!(topStringOfStack=codeStack.pop()).startsWith("/*")))
{
}
}
}
}
else {
System.out.println("after// "+str);
}
}
return result;
}