2010-08-23 108 views
3

我的目標是分析java源文件以查找包含非註釋代碼的行號。由於StreamTokenizer具有slashStarComments()和slashSlashComments(),我想我會用它來過濾只有註釋和沒有代碼的行。使用StreamTokenizer過濾Java註釋

下面的程序打印行號和該行上的任何字符串標記,對於每行不具有註釋的行。

它的工作原理的時間,但有時不... 例如,行號得到跳過飄飛與log4j的下列源文件中的註釋行144開始時,Category.java: 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. 有關如何過濾評論的任何替代想法將不勝感激。

回答

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. 
*/ 

...兩條空行將行數偏移兩位。所以第146行被報告爲第144行,等等。但是不知道爲什麼。如果您將註釋更改爲以下內容:

/** 
    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中的錯誤! 我複製類,並將其重命名爲MyStreamTokenizer,改線700:

if (c == '\n') 

while (c == '\n') 

和它的作品! 通過

@author James Gosling 
@since JDK1.0 
0

一個罐子,源中央Maven回購可我只是發現有在SDN的缺陷數據庫不固定的錯誤,錯誤4517649標有「關閉,將不修復」。 http://localhost/hawk.html?gwt.codesvr=127.0.0.1:9997&locale=en

由於兼容性的限制,我們 不會進一步發展這一傳統 類。XXXXX @ XXXXX 2002年2月14日

沒有解決方法,給出兩種:-(