我写了下面的程序来读取文件并跳过注释,它适用于单行注释,但不适用于多行注释。有谁知道为什么?我不需要担心Strings中的“//”。而且,只有Java的意见,即 “//” 和 “/ * * /”我如何跳过缓冲区阅读器的评论?
代码:
import java.io.*;
public class IfCounter2
{
public static boolean lineAComment(String line)
{
if (line.contains("//"))
return true;
return false;
}
public static boolean multiLineCommentStart(String line)
{
if (line.contains("/*"))
return true;
return false;
}
public static boolean multiLineCommentEnd(String line)
{
if (line.contains("*/"))
return true;
return false;
}
public static void main(String[] args) throws IOException
{
String fileName = args[0];
int numArgs = args.length;
int ifCount = 0;
// create a new BufferReader
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
line = reader.readLine();
// read from the text file
boolean multiLineComment = false;
while ((line = reader.readLine()) != null)
{
if (!multiLineCommentStart(line))
{
multiLineComment = true;
}
if (multiLineComment) {
if (!multiLineCommentEnd(line))
{
multiLineComment = false;
}
}
if (!lineAComment(line) && !multiLineComment)
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}
// create a new string with stringBuilder data
String tempString = stringBuilder.toString();
System.out.println(stringBuilder.toString());
}
}
你如何使用这些方法?除非我误解了这个问题,否则问题出现在代码中。 – Andy
在主要只是下面的方法:) – josh
对不起,没有看到滚动条...:/ – Andy