. 1. Obtain a File object directory tree below the folder is a folder called recursively until the folder is not found until the walk () method will start directory to the File object, then call recurseDirs:. Recursive calls
Package com.zachary.file; Import java.io.File; Import java.io.FilenameFilter; Import of java.util.ArrayList; Import the java.util.Iterator; Import java.util.List; Import java.util.regex.Pattern ; / ** * @author Zachary.Zheng * @version 1.0 * @date 2019 Nian 11 Yue 9 Ri * / public class Directory { / ** * Gets the file matches the regular folder name * local () is used to be known listfile () of File.list () to generate a variant array File * @param the dir * @param REGEX *@return * / public static File [] local (File the dir, Final String REGEX) { return dir.listFiles ( new new the FilenameFilter () { Private the Pattern = pattern of Pattern.compile (REGEX); @Override public Boolean Accept (File the dir, String name) { return Pattern.matcher ( new new file (name) .getName ()) the matches ();. } }); } / ** * Get regular matches the folder name * @param path * @param REGEX * @return */ public static File[] local(String path, final String regex) { return local(new File(path), regex); } public static class TreeInfo implements Iterable<File> { // 文件名称路径 public List<File> files = new ArrayList<>(); // 文件夹路径 public List<File> dirs = new ArrayList<>(); @Override public Iterator<File> iterator() { return files.iterator(); } void addAll(TreeInfo other) { files.addAll(other.files); dirs.addAll(other.dirs); } @Override public String toString() { return "TreeInfo [dirs=" + PPrint.pformat(dirs) + ", \n\nfiles=" + PPrint.pformat(files) + "]"; } } public static TreeInfo walk(String start, String regex) { return recurseDirs(new File(start), regex); } public staticTreeInfo Walk (File Start, String REGEX) { return recurseDirs (Start, REGEX); } public static TreeInfo Walk (String Start) { return recurseDirs ( new new File (Start), "*." ); } Public static TreeInfo Walk (File Start) { return recurseDirs (Start, "*." ); } / ** * Get tree * recurse: recursively * 1.local () is called using listfile () of File.list () variant of to produce an array of file * 2.walk () method will start directory to the file object, then call recurseDirs * // file name path to hold all the files * public List <file> files = new ArrayList <> (); * // directory path to the folder holding so List public * <File> = new new dirs the ArrayList <> (); * @param STARTDIR * @param REGEX * @return * / static TreeInfo recurseDirs (File STARTDIR, String REGEX) { TreeInfo Result = new new TreeInfo (); // file clip may be filtered for (Item file: Directory.local (STARTDIR,. "*" )) { IF (item.isDirectory ()) { result.dirs.add (Item); / * * 1. The following is a file folder folders recursively until there are no folders found so far. * 2. the directory structure of sub-folders are copied to the parent folder * / result.addAll(recurseDirs(item, regex)); } else { if(item.getName().matches(regex)) { result.files.add(item); } } } return result; } public static void main(String[] args) { if(args.length == 0) { System.out.println(walk(".")); } else { for (String arg : args) { System.out.println(walk(arg)); } } } } ///:~
2. PPrint formatted print directory tree tool
package com.zachary.file; import java.util.Arrays; import java.util.Collection; /** * @author Zachary.Zheng * @version 1.0 * @date 2019年11月9日 */ public class PPrint { public static String pformat(Collection<?> c) { if(c.size() == 0) { return "[]"; } StringBuffer result = new StringBuffer("["); for (Object elem : c) { if(c.size() != 1) { result.append("\n "); } result.append(elem); } if(c.size() != 1) { result.append("\n"); } result.append("]"); return result.toString(); } public static void pprint(Collection<?> c) { System.out.println(pformat(c)); } public static void pprint(Object [] c) { System.out.println(pformat(Arrays.asList(c))); } } ///:~
3. Create a tool that can walk through the catalog, and manage them to the directory structure according to Strategy objects (this is another example of the strategy pattern)
Package Penalty for com.zachary.file; Import java.io.File; Import java.io.IOException; / ** * @author Zachary.Zheng * @version 1.0 * @date 2019 Nian 11 Yue 9 Ri * / public class the Process Files { / ** * define the callback function interface * realized when calling * @author Zachary.Zheng * @version 1.0 * @date 2019 Nian 11 Yue 9 Ri * / public interface at Strategy { void Process (File File); } Private at Strategy at Strategy; private String ext; public ProcessFiles(Strategy strategy, String ext) { super(); this.strategy = strategy; this.ext = ext; } public ProcessFiles() { super(); } public void start(String [] args) { try { if(args.length == 0) { processDirectoryTree(new File(".")); } else { for (String arg : args) { File fileArg = new File(arg); if(fileArg.isDirectory()) { processDirectoryTree(fileArg); } else { if(!arg.endsWith("." + ext)) { arg += "." + ext; } // 执行回调函数 strategy.process(new File(arg).getCanonicalFile()); } } } } catch (Exception e) { // TODO: handle exception } } public void processDirectoryTree(File root) throws IOException { for(File file: Directory.walk(root.getAbsolutePath(), ".*\\."+ext)) { // 执行回调函数 strategy.process(file.getCanonicalFile()); } } public static void main(String[] args) { new ProcessFiles(new ProcessFiles.Strategy() { // 回调函数 public void process(File file) { System.out.println(file); } }, "java").start(args);; } } /* Output: (sample) E:\\javaBaseLearn\\IOStream\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\Directory.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList2.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\DirList3.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\PPrint.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\ProcessFiles.java E:\\javaBaseLearn\\IOStream\\workSpace\\java-io-stream\\src\\com\\zachary\\io\\util\\TreeInfo.java *///:~
4. Inspection and create directories
package com.zachary.file; import java.io.File; import java.io.IOException; /** * @author Zachary.Zheng * @version 1.0 * @date 2019年11月10日 */ public class MakeDirectories { private static void usage() { System.err.println( "Usage:MakeDirectories path1 ...\n" + "Creates each path\n" + "Usage:MakeDirectories -d path1 ...\n" + "Creates each path\n" + "Usage:MakeDirectories -r path1 path2\n" + "Renames from path1 to path2" ); System.exit(1); } private static void fileData(File f) { System.out.println( "Absolute path: " + f.getAbsolutePath() + "\n Can read: " + f.canRead() + "\n Can write: " + f.canWrite() + "\n getName: " + f.getName() + "\n getParent: " + f.getParent() + "\n getPath: " + f.getPath() + "\n length: " + f.length() + "\n lastModified: " + f.lastModified() ); if(f.isFile()) { System.out.println("It's a file"); } else if(f.isDirectory()) { System.out.println("It's s directory"); } } public static void main(String[] args) throws IOException { if(args.length < 1) { usage(); } // 读 if(args[0].equals("-r")) { if(args.length != 3) { usage(); } File Old = new new File (args [. 1 ]), the rename = new new File (args [2 ]); // rename failed return success returns true to false System.out.println ( "renameTo:" + old.renameTo (the rename)) ; fileData (Old); fileData (the rename); return ; // the Exit main } // the Add file // -add MakeDirectoriesTest MakeDirectoriesTest.txt IF (args [0] .equals ( "- the Add" )) { IF (args. ! = length. 3 ) { Usage (); } File f = new File(args[1], args[2]); if(!f.exists()) { // 创建文件 MakeDirectoriesTest.txt f.createNewFile(); System.out.println("created..." + f); } return; // Exit main } int count = 0; boolean del = false; if(args[0].equals("-d")) { count++; del = true; } count--; while (++count < args.length) { File f = new File(args[count]); if(f.exists()) { System.out.println(f + "exists"); if(del) { System.out.println("deleting..." + f); f.delete(); } } else { // 文件不存在 if(!del) { f.mkdirs(); System.out.println("created..." + f); } } fileData(f); } } }