import java.io.*;
import java.util.ArrayList;
public class getAllJava
{
private static int blankLine = 0;// 空行
private static int realLine = 0;// 长度不为0的行
private static ArrayList<File> arr = new ArrayList<File>();// 用于存放遍历到的文件
public static void main(String[] args) throws IOException
{
getJavaFile(new File("d:\\java"));
print();
}
public static void getJavaFile(File f) throws IOException// 迭代得到文件,并调用
// 读取文件行数方法 。
{
File[] fs = f.listFiles();
for (int x = 0; x < fs.length; x++)
{
if(fs[x].isDirectory())
getJavaFile(fs[x]);
else if(fs[x].isFile())
if(fs[x].getName().endsWith(".java"))
{
lineNum((fs[x]));
}
}
}
public static void lineNum(File f) throws IOException// 读取文件行数
{
if(!f.isFile())
throw new RuntimeException("打不开的文件");
BufferedReader br;
br = new BufferedReader(new FileReader(f));
String str;
while ((str = br.readLine()) != null)
{
if(str.isEmpty())
blankLine++;
else
realLine++;
}
}
public static void print()
{
System.out.println("空行" + blankLine);
System.out.println("有效行数" + realLine);
}
}
这个代码是我在学完IO之后写的。只能判断空行和非空行,依据的是String,lenth() 是否为空。很简单的代码。