override log exce blog cor param 文件 direct exc
首先获取指定目录下的所有文件目录,存入 List 集合中,然后创建文本文件将 List 遍历写入文本中保存。
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //获取IO目录下的所有java文件
- File dir = new File("H:\\workspace\\IO");
- List < File > list = fileList(dir, ".java"); //路径列表,传入过滤器
- //获取路径下的符合条件的文件后,写入一个txt中
- File destFile = new File("H:\\workspace\\Testfile\\javaList.txt");
- write2File(list, destFile);
- }
- /**
- * 定义获取指定过滤器条件的集合
- * @param dir 路径
- * @param string 后缀.java
- * @return
- */
- public static List < File > fileList(File dir, String suffix) {
- //1.定义集合
- List < File > list = new ArrayList < File > ();
- //2.过滤器
- FileFilter filter = new FileFilterBySuffix(suffix);
- getFileList(dir, list, filter);
- return list;
- }
- /**
- * 定义一个获取指定过滤器条件的集合
- * 多级目录下,传递list
- * @param dir 路径
- * @param list 文件集合
- * @param filter 过滤器
- */
- public static void getFileList(File dir, List < File > list, FileFilter filter) {
- File[] files = dir.listFiles();
- for (File file: files) {
- if (file.isDirectory()) {
- getFileList(file, list, filter); //递归
- } else {
- //过滤文件
- if (filter.accept(file)) {
- list.add(file); //添加
- }
- }
- }
- }
- }
- public class FileFilterBySuffix implements FileFilter {
- private String suffix;
- public FileFilterBySuffix(String suffix) {
- super();
- this.suffix = suffix;
- }
- @Override public boolean accept(File pathname) {
- // TODO Auto-generated method stub
- return pathname.getName().endsWith(suffix);
- }
- }
Java I/O--- 获取文件目录并写入到文本
- /**
- * 将list写入txt中
- * @param list 文件列表
- * @param destFile 存储对象java文件列表
- */
- private static void write2File(List < File > list, File destFile) {
- // TODO Auto-generated method stub
- BufferedWriter bufw = null;
- try {
- //使用字符缓冲区对象BufferedWriter
- bufw = new BufferedWriter(new FileWriter(destFile));
- //遍历list,写入绝对路径
- for (File file: list) {
- bufw.write(file.getAbsolutePath()); //写入绝对路径
- bufw.newLine(); //换行
- bufw.flush(); //刷新纪录
- }
- } catch(Exception e) {
- // TODO: handle exception
- } finally {
- if (bufw != null) {
- try {
- bufw.close();
- } catch(IOException e) {
- // TODO Auto-generated catch block
- throw new RuntimeException();
- }
- }
- }
- }
override log exce blog cor param 文件 direct exc
原文:https://www.cnblogs.com/zhuweiheng/p/8149033.html
来源: http://www.bubuko.com/infodetail-2445465.html