在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的檔案行數,同時具有很好的可擴充性,可以根據需要修改搜尋和過濾條件。