在Java开发中,经常需要对文件进行读写、查找和操作,因此,掌握文件操作技能非常重要。
以下是具体代码实现:
1、通过递归方式查找文件:
public static List<File> searchFiles(String folderPath, String suffix) {
List<File> result = new ArrayList<>();
File folder = new File(folderPath);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
result.addAll(searchFiles(file.getAbsolutePath(), suffix));
} else {
if (file.getName().endsWith(suffix)) {
result.add(file);
}
}
}
}
return result;
}
通过递归方式,我们可以遍历指定文件夹下所有的子文件夹和文件,并且只选取符合指定后缀名的文件进行存储和统计。
2、计算每个文件的行数:
public static int countLines(File file) throws IOException {
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
count++;
}
br.close();
return count;
}
该方法使用BufferedReader逐行读取文件,并统计每个文件的行数。
3、统计所有文件的行数并返回结果:
public static int countTotalLines(List<File> files) throws IOException {
int totalLines = 0;
for (File file : files) {
totalLines += countLines(file);
}
return totalLines;
}
该方法遍历所有符合条件的文件,调用countLines方法计算每个文件的行数,并将所有文件的行数累加起来返回结果。
完整的代码如下所示:
import java.io.*;
import java.util.*;
public class FileLineCounter {
public static void main(String[] args) throws IOException {
String folderPath = "D:/test";
String suffix = ".java";
List<File> files = searchFiles(folderPath, suffix);
int totalLines = countTotalLines(files);
System.out.println("Total lines of code: " + totalLines);
}
public static List<File> searchFiles(String folderPath, String suffix) {
List<File> result = new ArrayList<>();
File folder = new File(folderPath);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
result.addAll(searchFiles(file.getAbsolutePath(), suffix));
} else {
if (file.getName().endsWith(suffix)) {
result.add(file);
}
}
}
}
return result;
}
public static int countLines(File file) throws IOException {
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
count++;
}
br.close();
return count;
}
public static int countTotalLines(List<File> files) throws IOException {
int totalLines = 0;
for (File file : files) {
totalLines += countLines(file);
}
return totalLines;
}
}
该程序可以统计指定文件夹下所有后缀名为.java的文件行数,同时具有很好的可扩展性,可以根据需要修改搜索和过滤条件。