使用StreamTokenizer过滤Java注释

3
我的目标是分析Java源文件,查找包含非注释代码的行号。由于StreamTokenizer具有slashStarComments()和slashSlashComments()方法,所以我想使用它来过滤只有注释而没有代码的行。

以下程序打印每个包含非注释内容的行的行号和任何字符串标记。

它大部分时间都有效,但有时候会出现问题...例如,在log4j的以下源文件Category.java中,从注释行144开始,有时会跳过一些行: http://logging.apache.org/log4j/1.2/xref/org/apache/log4j/Category.html StreamTokenizer有时会在javadoc注释结尾处跳过一些行。

这是我的代码:

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;

public class LinesWithCodeFinder {
 public static void main(String[] args) throws IOException {
  String filePath = args[0];
  Reader reader = new FileReader(filePath);
  StreamTokenizer tokenizer = new StreamTokenizer(reader);
  tokenizer.slashStarComments(true);
  tokenizer.slashSlashComments(true);
  tokenizer.eolIsSignificant(false);
int ttype = 0; int lastline = -1; String s = ""; while (ttype != StreamTokenizer.TT_EOF) { ttype = tokenizer.nextToken(); int lineno = tokenizer.lineno(); String sval = ttype == StreamTokenizer.TT_WORD ? tokenizer.sval : ""; if (lineno == lastline) { s += " " + sval; } else { if (lastline != -1) System.out.println(lastline + "\t" + s); s = sval; } lastline = lineno; } } }
  1. 有人了解StreamTokenizer的行为原因吗?

  2. 欢迎提供任何过滤掉注释的替代方法。

4个回答

1

注释中的段落会影响行数计算。从第137行开始...

  /**
     This constructor created a new <code>Category</code> instance and
     sets its name.

     <p>It is intended to be used by sub-classes only. You should not
     create categories directly.

     @param name The name of the category.
*/

...这两行空白行导致行数偏移了两行。因此,报告的是第144行而不是第146行等等。不过我不确定为什么会这样。如果你将注释更改为以下内容:

 /**
     This constructor created a new <code>Category</code> instance and
     sets its name.    
     <p>It is intended to be used by sub-classes only. You should not
     create categories directly.    
     @param name The name of the category.
*/

...在注释后的行号将会正确报告。


1

我觉得我找到了StreamTokenizer中的bug! 我复制了这个类并将其重命名为MyStreamTokenizer,并且将第700行改成了:

if (c == '\n')

while (c == '\n')

它可以工作!

一个讨厌的错误。

@author  James Gosling 
@since   JDK1.0

0

我刚发现SDN的错误数据库中有一个未修复的错误,编号为4517649的错误被标记为“已关闭,不会修复”。 http://localhost/hawk.html?gwt.codesvr=127.0.0.1:9997&locale=en

由于兼容性限制,我们将不会进一步开发这个遗留类。xxxxx@xxxxx 2002-02-14

也没有给出解决方法 :-(


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接