Skip to content

Instantly share code, notes, and snippets.

@froop
Created May 9, 2011 15:26
Show Gist options
  • Select an option

  • Save froop/962736 to your computer and use it in GitHub Desktop.

Select an option

Save froop/962736 to your computer and use it in GitHub Desktop.
[Java] Javaソースからコメントを削除するツール
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
/**
* Javaソースのコメントを削除
* 行コメントとブロックコメントがネストしているような場合はうまくいかない時があるので注意
* 使用例: java CommentDelete < Test.java > Test.txt
*/
public class CommentDelete {
private static String LINE_SEP = System.getProperty("line.separator");
// 標準入力(Javaソース)→処理→標準出力(コメントを削除したソース)
public static void main(String[] args) throws IOException {
String text = readText(System.in);
text = deleteLineComment(text);
text = deleteBlockComment(text);
text = deleteBlankLine(text);
System.out.print(text);
}
// 行コメント(「//」以降)削除
public static String deleteLineComment(String src) {
StringBuffer buf = new StringBuffer();
boolean isLineComment = false;
for (int i = 0; i < src.length(); i++) {
char ch = src.charAt(i);
if (isLineComment) {
if (ch == LINE_SEP.charAt(0)) {
isLineComment = false;
}
} else if (ch == '/' && src.charAt(i + 1) == '/') {
isLineComment = true;
} else {
buf.append(ch);
}
}
return buf.toString();
}
// ブロックコメント(「/*」から「*/」まで)削除
public static String deleteBlockComment(String src) {
StringBuffer buf = new StringBuffer();
boolean isBlockComment = false;
for (int i = 0; i < src.length(); i++) {
char ch = src.charAt(i);
if (isBlockComment) {
if (ch == '/' && src.charAt(i - 1) == '*') {
isBlockComment = false;
}
} else if (ch == '/' && src.charAt(i + 1) == '*') {
isBlockComment = true;
} else {
buf.append(ch);
}
}
return buf.toString();
}
// 空行削除
public static String deleteBlankLine(String src) throws IOException {
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new StringReader(src));
String inLine;
while ((inLine = reader.readLine()) != null) {
if (!inLine.matches("^\\s*$")) {
buf.append(inLine);
buf.append(LINE_SEP);
}
}
return buf.toString();
}
// InputStreamからテキストを取得
private static String readText(InputStream in) throws IOException {
InputStreamReader inReader = new InputStreamReader(in);
StringBuffer sBuf = new StringBuffer();
int ch;
while ((ch = inReader.read()) != -1) {
sBuf.append((char) ch);
}
return sBuf.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment