读取Java文件时如何忽略注释语句/*.....*/? [英] How can I ignore comments statements /*.....*/ when i reading java file?
本文介绍了读取Java文件时如何忽略注释语句/*.....*/?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何忽略以 / *
开头并以
* / $结尾的注释语句c $ c>例如:
/ *问题是.. * /
或
/ *问题非常困难* /
,,我想逐行阅读Java文件时删除这些语句
How can i ignore the comment statements that begin with "/*"
and ends with
"*/"
for example: /*the problem is..*/
or
/* problem is very difficult */
,,i want to remove these statement when i reading java file line by line
public class filename1 {
public static void main (String args[])
{
try {
fileName = "C:\\NetBeansProjects\\filename\\src\\filename\\filename.java";
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while (line !=null) {
for( int i=0;i<line.length();i++)
{
b=line.indexOf("/",i);
ee=line.indexOf("*",i);
if(b!=-1 && ee!=-1)
v=line.indexOf("*/",i);
if (v==-1)
line=" ";
}
System.out.println(line);
line = br.readLine();
}}
catch (IOException e)
{
e.printStackTrace();
}
}
}
推荐答案
简单地包括:
int index = str.indexOf("/*");
while(index != -1) {
str = str.substring(0, index) + str.substring(str.indexOf("*/")+2);
index = str.indexOf("/*");
}
编辑:
假设您必须考虑您在注释中被字符串开头或结尾打断的片段:
Edit2:
现在。。此外,假设您必须输入文字字符串 / *
或 * /
str = str.replace("\"/*\"", "literal_string_open_comment");
str = str.replace("\"*/\"", "literal_string_close_comment");
int start = str.indexOf("/*"), end = str.indexOf("*/");
while(start > -1 || end > -1) {
if(start != -1) {
if(end != -1) {
if(end < start) {
str = str.substring(end+2);
} else {
str = str.substring(0, start) + str.substring(end+2);
}
} else {
str = str.substring(0, start);
}
} else {
str = str.substring(end+2);
}
start = str.indexOf("/*");
end = str.indexOf("*/");
}
str = str.replace("literal_string_open_comment", "\"/*\"");
str = str.replace("literal_string_close_comment", "\"*/\"");
这篇关于读取Java文件时如何忽略注释语句/*.....*/?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文