import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Question1 {
private static int validnum = 0;//有效行数private static final Logger LOGGER = LoggerFactory.getLogger(Question1.class);
private static final String INPUT_File_NAME = "/StringUtils.java";
private static final String OUTPUT_FILE_NAME = "/validLineCount.txt";
public static void main(String[] args) throws Exception {
Question1 question = new Question1();
String url = Question1.class.getResource("/").getFile();
question.validLine(url + INPUT_File_NAME);
question.print(url + OUTPUT_FILE_NAME);
}
public void validLine(String path1) throws Exception {
File file = new File(path1);
if (!file.exists() || !file.getName().endsWith(".java")){
return;
}
readFile(file);
}
public void readFile(File file) throws Exception {
//读文件
if (file.isFile()) {
count(file);
} else if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File ff : files) {
readFile(ff);
}
}
}
}
public void count(File f) throws Exception {
//统计有效行数
FileInputStream fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String tmp = null;
int status = 0;//标记状态
try {
while ((tmp = br.readLine()) != null) {
tmp = tmp.trim();
if (tmp.startsWith("/**")) {
//文档注释
status = 1;
} else if (tmp.startsWith("/*")) {
//多行注释
status = 2;
}
if (tmp == null || "".equals(tmp) || tmp.startsWith("//")
|| tmp.startsWith("/*") && tmp.endsWith("*/")) {
//空白行、单行注释
} else if (status == 1 || status == 2) {
//do nothing.
} else {
validnum++;
}
if (tmp.endsWith("*/")) {
status = 0;
}
}
} catch (Exception e) {
LOGGER.error("统计有效行数失败!");
} finally {
closeIgnoreException(br);
}
}
public void print(String path2) throws Exception {
File file2 = new File(path2);
if (!file2.exists()) {
file2.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(path2));
try {
bw.write(Integer.toString(validnum));
} catch (Exception e) {
LOGGER.error("打印到文件失败!");
} finally {
closeIgnoreException(bw);
}
}
public static void closeIgnoreException(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
}
}
}
}