这道题与上面这道题出自于我今天的面试,实现的需求大同小异。但是我却不会,没能做出来,这里做一下笔记。
package com.example.study_source.pager;
import org.apache.commons.io.FilenameUtils; import org.junit.Test;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader;
public class FileListTest {
private static String getLevel(int level) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) { sb.append("|--"); } return sb.toString(); }
public static void getAllFiles(File dir, int level) { System.out.println(getLevel(level) + dir.getName()); level++; File[] files = dir.listFiles(); for (int j = 0; j < files.length; j++) { if (files[j].isDirectory()) { getAllFiles(files[j], level); } else { System.out.println(getLevel(level) + files[j]); } } }
@Test public void test1() { String docPath = "E:\\webp"; File file = new File(docPath); getAllFiles(file, 0); }
public static void getEachFileCnt(File dir, int level) {
level++; try { File[] files = dir.listFiles(); for (int j = 0; j < files.length; j++) { if (files[j].isDirectory()) { getEachFileCnt(files[j], level); } else {
String fileName = files[j].getName(); String suffix = FilenameUtils.getExtension(fileName); if ("txt".equalsIgnoreCase(suffix)) { FileReader fileReader = new FileReader(files[j]); BufferedReader bufferedReader = new BufferedReader(fileReader); String strLine = ""; long lineCnt = 0L; while ((strLine = bufferedReader.readLine()) != null) { lineCnt++; } System.out.println("文件:" + files[j].getName() + " 的行数为:" + lineCnt); } } } } catch (Exception e) { e.printStackTrace(); } }
@Test public void test2() { String docPath = "E:\\webp"; File file = new File(docPath); getEachFileCnt(file, 0); }
}
|