要求:
给定一个字符串形式的文件,每行是一个字符串。希望在注释行中找到“abc”,如果有返回true,没有返回false。规定两种注释方式:// 与 /* */。
代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class test {
public static boolean check(String path) {
try {
FileReader fr = new FileReader(path);// 字符流
BufferedReader br = new BufferedReader(fr);// 缓冲流
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String content = sb.toString();
// 单行
if (content.contains("//") && content.contains("abc")) {
return true;
}
// 多行
if (content.contains("/*") && content.contains("abc") && content.contains("*/")) {
int start = content.indexOf("/*");
int end = content.indexOf("*/");
String innerContent = "";
if (start <= end) {// */ /* abc
innerContent = content.substring(start, end);
}
if (innerContent.contains("abc")) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
String path = "文件绝对路径";
boolean res = check(path);
System.out.println("result:" + res);
}
}
有用点个赞,谢谢giegie!
:)