java目录相关操作 示例代码
java目录相关操作 示例代码
package org.rui.io; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.regex.Pattern; /** * 目录列表器 测试 * * @author lenovo * */ //Args:"C:/Users/lenovo/Pictures/screen/*\.jpg" public class DirList { public static void main(String[] args) { String[] argss=new String[1]; String s=DirectoryDemo.class.getPackage().getName().replace(".","/"); String dirPath=new File("").getAbsolutePath()+"\\src\\"+s; //path="."; argss[0]="D.*\\.java"; File path=new File(dirPath); String[] list = null; if(argss.length==0) { list=path.list(); }else { System.out.println("all file list==>"+Arrays.toString(path.list())); //显示文件夹下面的文件并用正则匹配 list=path.list(new DirFilter(argss[0])); } //排序打印 Arrays.sort(list,String.CASE_INSENSITIVE_ORDER); for(String dirItem:list) System.out.println(dirItem); } } /** * output: all file list==>[D.txt, Directory.java, DirectoryDemo.java, DirList.java, fout, inout, Main.java, PPrint.java, zzz.class] Directory.java DirectoryDemo.java DirList.java * */ /** * 这是一个策略模式的例子 * @author lenovo * */ class DirFilter implements FilenameFilter { private Pattern pattern; public DirFilter(String regex) { this.pattern=Pattern.compile(regex); } public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }
package org.rui.io; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; /** * 目录实用工具 * @author lenovo * */ public class Directory { public static File[] local(File dir,final String regex) { return dir.listFiles(new FilenameFilter() { private Pattern pa=Pattern.compile(regex); public boolean accept(File dir, String name) { return pa.matcher(name).matches(); } }); } //overloaded重载 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<File>(); public List<File> dirs=new ArrayList<File>(); public Iterator<File> iterator() { return files.iterator(); } void addAll(TreeInfo other) { files.addAll(other.files); dirs.addAll(other.dirs); } public String toString() { return "dirs: "+PPrint.pformat(dirs)+ "\n\nfiles:"+PPrint.pformat(files); } public static TreeInfo walk(String start,String regex) { return recurseDirs(new File(start),regex); } public static TreeInfo walk(File f,String regex) { return recurseDirs(f,regex); } public static TreeInfo walk(File f) { return recurseDirs(f,".*"); } public static TreeInfo walk(String start) { return recurseDirs(new File(start),".*"); } //递归 static TreeInfo recurseDirs(File f,String reg) { TreeInfo result=new TreeInfo(); for(File item :f.listFiles()) { if(item.isDirectory()) { result.dirs.add(item);//添加目录集合 result.addAll(recurseDirs(item,reg));//递归回方法 循环子目录 }else { if(item.getName().matches(reg)) { result.files.add(item);//添加文件 } } } return result; } //////////////////////////mian public static void main(String[] args) { String[] argss=new String[1]; //C:\\Users\\lenovo\\Pictures\\screen argss[0]="."; if(argss.length==0) System.out.println(walk(".")); else for(String arg:argss){ System.out.println(walk(arg)); } } } } /**output: * //result.addAll(recurseDirs(item,reg));//以下是不递归的输出,文件太多 不好理解 dirs: [.\.settings, .\bin, .\src] files:[.\.classpath, .\.project] --------------------------------------------------------------------- ----------格式化后的输出-------------- --------------------------------------------------------------------- dirs: [ .\.settings .\bin .\src ] files:[ .\.classpath .\.project ] */
package org.rui.io; import java.util.Arrays; import java.util.Collection; /** * 灵巧打印机 以使输出更容易浏览 * @author lenovo * */ public class PPrint { public static String pformat(Collection<?> c) { if(c.size()==0)return "[]"; StringBuilder result=new StringBuilder("["); 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))); } }
package org.rui.io; import java.io.File; import java.util.regex.Pattern; public class DirectoryDemo { public static void main(String[] args) { String s=DirectoryDemo.class.getPackage().getName().replace(".","/"); String path=new File("").getAbsolutePath()+"\\src\\"+s; //System.out.println(path); //path="."; PPrint.pprint(Directory.TreeInfo.walk(path).dirs); //all files beginning with "t" for(File f:Directory.local(path,"D.*")) System.out.println(f); System.out.println("----------------"); for(File f:Directory.local(path, "D.*\\.java")) System.out.println(f); System.out.println("================"); //class files containing "z" or "Z" for(File f:Directory.TreeInfo.walk(path,".*[Zz].*\\.class")) System.out.println(f); } } /** [ D:\Users\liangrui\workspace\thinking\src\org\rui\io\fout D:\Users\liangrui\workspace\thinking\src\org\rui\io\fout\f D:\Users\liangrui\workspace\thinking\src\org\rui\io\inout ] D:\Users\liangrui\workspace\thinking\src\org\rui\io\D.txt D:\Users\liangrui\workspace\thinking\src\org\rui\io\Directory.java D:\Users\liangrui\workspace\thinking\src\org\rui\io\DirectoryDemo.java D:\Users\liangrui\workspace\thinking\src\org\rui\io\DirList.java ---------------- D:\Users\liangrui\workspace\thinking\src\org\rui\io\Directory.java D:\Users\liangrui\workspace\thinking\src\org\rui\io\DirectoryDemo.java D:\Users\liangrui\workspace\thinking\src\org\rui\io\DirList.java ================ D:\Users\liangrui\workspace\thinking\src\org\rui\io\zzz.class */
package org.rui.io; import java.io.File; import java.io.IOException; import java.util.regex.Pattern; /** * 更近一步创建一个目录工具,它可以在目录中穿行, * 这是策略设计模式的另一个示例 * Strategy 接口内嵌在processFile中,使得如果你希望实现它,就必须实现ProcessFiles.Strategy * 它为读者提供了更多的上下文信息。 * * * * @author lenovo * */ public class ProcessFiles { //策略 public interface Strategy { void process(File file); } private Strategy strategy; private String ext; public ProcessFiles(Strategy strategy,String ext) { this.strategy=strategy; this.ext=ext; } 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) { throw new RuntimeException(e); } } ////////walk=步行 private void processDirectoryTree(File root) throws IOException { for(File file:Directory.TreeInfo.walk( root.getAbsoluteFile(), ".*\\."+ext )) strategy.process(file.getCanonicalFile()); } //demonstration of how to use public static void main(String[] args) { new ProcessFiles(new ProcessFiles.Strategy() { public void process(File file) { System.out.println(file); } }, "java").start(args);; } } /**output: D:\Users\liangrui\workspace\thinking\src\Concatenation.java D:\Users\liangrui\workspace\thinking\src\org\rui\array\AssemblingMultidimensionalArrays.java D:\Users\liangrui\workspace\thinking\src\org\rui\array\AutoboxingArrays.java D:\Users\liangrui\workspace\thinking\src\org\rui\array\Bean.java ....................... .............. */
package org.rui.io; import java.io.File; /** * 目录检查及创建 * @author lenovo * */ public class MakeDirectories { //提示信息 private static void usage() { System.err.println( "Usage:MakeDirectories path1...\n"+ "Creates each path\n"+ "usage:makedirectories -d path1....\n"+ "deletes each path\n"+ "usage make directories -r path1 path2\n"+ "Renames from path1 to path2" ); System.exit(0); } //输出文件信息 private static void fileDate(File f) { System.out.println("absolute path:"+f.getAbsolutePath() +"\ncal read:"+f.canRead() +"\ncan Write:"+f.canWrite() +"\n name:"+f.getName() +"\nparent:"+f.getParent() +"\nlength:"+f.length() +"\npath:"+f.getPath() +"\nlastmodiffied:"+f.lastModified() ); if(f.isFile()) System.out.println("it is a file"); else if(f.isDirectory()) System.out.println("it s a directory"); } /////////////////////main test/////////////////////////////////////// public static void main(String[] args) { String argss[]=new String[1]; argss[0]="MakeDirectoriesTest"; if(argss.length<1) usage(); if(argss[0].equals("-r")) { if(argss.length!=3) { usage(); } File old=new File(argss[1]),rname=new File(argss[2]); old.renameTo(rname); fileDate(old); fileDate(rname); return; //exit main } int count=0; boolean del=false; if(argss[0].equals("-d")) { count++; del=true; } count--; while(++count<argss.length) { File f=new File(argss[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); } } fileDate(f); } } } /**output:(80% match) created:MakeDirectoriesTest absolute path:D:\Users\liangrui\workspace\thinking\MakeDirectoriesTest cal read:true can Write:true name:MakeDirectoriesTest parent:null length:0 path:MakeDirectoriesTest lastmodiffied:1403013856223 it s a directory */
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。