Java的动手动脑(七)
日期:2018.11.18
博客期:025
星期日
Part 1:使用 Files.walkFileTree()来找出指定文件夹下大小大于1KB的文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package temp; 2 3 import java.io.IOException; 4 import java.nio.file.FileVisitResult; 5 import java.nio.file.Files; 6 import java.nio.file.Path; 7 import java.nio.file.Paths; 8 import java.nio.file.SimpleFileVisitor; 9 import java.nio.file.attribute.BasicFileAttributes; 10 import java.util.LinkedList; 11 import java.util.List; 12 13 public class FindFile2 { 14 public void test1() throws IOException{ 15 Path path = Paths.get("D:\\test\\hold1"); 16 //Path path = fileSystem.getPath("c:/windows"); 17 List<String> result = new LinkedList<String>(); 18 Files.walkFileTree(path,new FilterFilesVisitor4(result)); 19 System.out.println("result.size()=" + result.size()); 20 for (String name : result) { 21 System.out.println(name); 22 } 23 } 24 public void test2() throws IOException{ 25 Path path = Paths.get("D:\\test\\hold1"); 26 //Path path = fileSystem.getPath("c:/windows"); 27 List<String> result = new LinkedList<String>(); 28 Files.walkFileTree(path,new FilterFilesVisitor(result)); 29 System.out.println("result.size()=" + result.size()); 30 for (String name : result) { 31 System.out.println(name); 32 } 33 } 34 public void test3() throws IOException{ 35 Path path = Paths.get("D:\\test\\hold1"); 36 List<String> result = new LinkedList<String>(); 37 Files.walkFileTree(path,new FilterFilesVisitor2(result)); 38 System.out.println("result.size()=" + result.size()); 39 for (String name : result) { 40 System.out.println(name); 41 } 42 } 43 public void test4() throws IOException{ 44 Path path = Paths.get("D:\\test\\hold1"); 45 List<String> result = new LinkedList<String>(); 46 Files.walkFileTree(path,new FilterFilesVisitor3(result)); 47 System.out.println("result.size()=" + result.size()); 48 for (String name : result) { 49 System.out.println(name); 50 } 51 } 52 public static void main(String[] args) throws IOException { 53 FindFile2 t = new FindFile2(); 54 t.test1(); 55 //t.test2(); 56 //t.test3(); 57 //t.test4(); 58 } 59 60 } 61 class FilterFilesVisitor extends SimpleFileVisitor<Path> { 62 63 private List<String> result = new LinkedList<String>(); 64 65 public FilterFilesVisitor(List<String> result) { 66 this.result = result; 67 } 68 69 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 70 if (file.toString().endsWith(".txt")) { 71 result.add(file.toString()); 72 } 73 return FileVisitResult.CONTINUE; 74 } 75 } 76 class FilterFilesVisitor2 extends SimpleFileVisitor<Path> { 77 78 private List<String> result = new LinkedList<String>(); 79 80 public FilterFilesVisitor2(List<String> result) { 81 this.result = result; 82 } 83 84 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 85 if (file.toString().endsWith(".java")) { 86 result.add(file.toString()); 87 } 88 return FileVisitResult.CONTINUE; 89 } 90 } 91 class FilterFilesVisitor3 extends SimpleFileVisitor<Path> { 92 93 private List<String> result = new LinkedList<String>(); 94 95 public FilterFilesVisitor3(List<String> result) { 96 this.result = result; 97 } 98 99 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 100 if (file.toString().endsWith(".txt")&&(file.toString().contains("no")||file.toString().contains("on"))) { 101 result.add(file.toString()); 102 } 103 return FileVisitResult.CONTINUE; 104 } 105 } 106 class FilterFilesVisitor4 extends SimpleFileVisitor<Path> { 107 108 private List<String> result = new LinkedList<String>(); 109 110 public FilterFilesVisitor4(List<String> result) { 111 this.result = result; 112 } 113 114 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 115 if (file.toFile().length()>1024) { 116 result.add(file.toString()); 117 } 118 return FileVisitResult.CONTINUE; 119 } 120 }
运行截图:
解说:这个是总体的代码,test1对应Part1,test2、3对应Part2和test4对应Part3,而我们的区别就在于判定条件上,File类的length()方法,求得文件的大小,求出的值为long类型,实际上就是文件有多少B(字节)。
Part 2:使用 Files.walkFileTree()来找出指定文件夹下以.txt和.java为后缀的文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package temp; 2 3 import java.io.IOException; 4 import java.nio.file.FileVisitResult; 5 import java.nio.file.Files; 6 import java.nio.file.Path; 7 import java.nio.file.Paths; 8 import java.nio.file.SimpleFileVisitor; 9 import java.nio.file.attribute.BasicFileAttributes; 10 import java.util.LinkedList; 11 import java.util.List; 12 13 public class FindFile2 { 14 public void test2() throws IOException{ 15 Path path = Paths.get("D:\\test\\hold1"); 16 //Path path = fileSystem.getPath("c:/windows"); 17 List<String> result = new LinkedList<String>(); 18 Files.walkFileTree(path,new FilterFilesVisitor(result)); 19 System.out.println("result.size()=" + result.size()); 20 for (String name : result) { 21 System.out.println(name); 22 } 23 } 24 public void test3() throws IOException{ 25 Path path = Paths.get("D:\\test\\hold1"); 26 List<String> result = new LinkedList<String>(); 27 Files.walkFileTree(path,new FilterFilesVisitor2(result)); 28 System.out.println("result.size()=" + result.size()); 29 for (String name : result) { 30 System.out.println(name); 31 } 32 } 33 public static void main(String[] args) throws IOException { 34 FindFile2 t = new FindFile2(); 35 t.test2(); 36 t.test3(); 37 } 38 39 } 40 class FilterFilesVisitor extends SimpleFileVisitor<Path> { 41 42 private List<String> result = new LinkedList<String>(); 43 44 public FilterFilesVisitor(List<String> result) { 45 this.result = result; 46 } 47 48 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 49 if (file.toString().endsWith(".txt")) { 50 result.add(file.toString()); 51 } 52 return FileVisitResult.CONTINUE; 53 } 54 } 55 class FilterFilesVisitor2 extends SimpleFileVisitor<Path> { 56 57 private List<String> result = new LinkedList<String>(); 58 59 public FilterFilesVisitor2(List<String> result) { 60 this.result = result; 61 } 62 63 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 64 if (file.toString().endsWith(".java")) { 65 result.add(file.toString()); 66 } 67 return FileVisitResult.CONTINUE; 68 } 69 }
运行截图:
解说:实际上这个就是继承一下 模板类 SimpleFileVisitor<Path> 的基础属性,然后自己定义我们自己的应用方法。不会的园友要实现文件的查找,只需按照以上模板修改file.toString().endsWith(".txt")里的语句即可,如上代码也可以直接写file.toString().endsWith(".txt")||file.toString().endsWith(".java"),嗯?是不是很好理解?
Part 3: Files.walkFileTree()来找出指定文件夹下含有特殊字符串的.txt文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class FilterFilesVisitor3 extends SimpleFileVisitor<Path> { 2 3 private List<String> result = new LinkedList<String>(); 4 5 public FilterFilesVisitor3(List<String> result) { 6 this.result = result; 7 } 8 9 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 10 if (file.toString().endsWith(".txt")&&(file.toString().contains("no")||file.toString().contains("on"))) { 11 result.add(file.toString()); 12 } 13 return FileVisitResult.CONTINUE; 14 } 15 }
运行截图:
解说:这个实际上,就是更改判定的问题,配合上边代码实现任务!
Part 4:看懂如下代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package file; 2 3 import java.nio.file.FileSystems; 4 import java.nio.file.Path; 5 import java.nio.file.Paths; 6 import java.nio.file.StandardWatchEventKinds; 7 import java.nio.file.WatchEvent; 8 import java.nio.file.WatchKey; 9 import java.nio.file.WatchService; 10 import java.util.HashMap; 11 import java.util.Map; 12 13 14 public class FileWatcherDemo { 15 16 /** 17 * @param args 18 */ 19 public static void main(String[] args) { 20 //创建一个WatchService对象,此对象将用于管理特定文件夹的变动信息队列。 21 try{WatchService service=FileSystems.getDefault().newWatchService(); 22 //此集合可保存多个文件夹的监控信息,当前只使用了一个 23 Map<WatchKey, Path> keyMap= new HashMap<WatchKey, Path>(); 24 Path path=Paths.get("D:\\test"); 25 //设置WatchService对象管理的内部队列,将保存指定的文件夹的创建、删除和修改事件信息 26 //返回的WatchKey对象可用于从事件队列中获取事件对象 27 WatchKey key=path.register(service, StandardWatchEventKinds.ENTRY_CREATE, 28 StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY); 29 keyMap.put(key, path); 30 31 do { 32 //开始监控,阻塞等待,当感兴趣的事件发生时,take()方法返回。 33 key=service.take(); 34 Path eventDir=keyMap.get(key); 35 //从事件队列中提取所有的事件 36 for (WatchEvent<?> event : key.pollEvents()) { 37 //是什么类型的事件? 38 WatchEvent.Kind<?> kind=event.kind(); 39 //是哪个对象发生了变动? 40 Path eventPath=(Path)event.context(); 41 System.out.println(eventDir+":"+kind+":"+eventPath); 42 } 43 } while (key.reset()); //reset方法重置此对象,让其可以重新接收信息 44 45 } catch (Exception e) { 46 47 } 48 49 } 50 51 }
运行结果:
解说:嗯,我是进行了对hold1文件夹里的文件进行改名,改了两次;之后是将本目录下的文件line2.bmp复制并粘贴到当前文件目录中,之后删掉原来的line2.bmp,之后改名line2 - 副本.bmp为line2.bmp文件,截图如上,就是针对此操作进行的监听,WatchKey对象可用于从事件队列中获取事件对象,其中path.register()方法是返回WatchKey对象的工具,需要Path给好路径。StandardWatchEventKinds就正如它的翻译一样,它是标准的监听事件种,其内部含有我们静态的事件成员,比如ENTRY_CREATE(创建)和ENTRY_DELETE(删除)等。WatchService service=FileSystems.getDefault().newWatchService();一句是
WatchService功能的伪构造方法,就是新建一个监听对象的方法...
简易UML类图:
Part 5:写一个小实例——文件分割工具、文件组合工具(目前领域只限txt文件)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.zhang.pvp; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.io.PrintWriter; 6 import java.util.Scanner; 7 8 public class TestZip { 9 public void FileFrozen(File x) throws FileNotFoundException{ 10 File f1,f2,f3; 11 f1 = new File("file/part1.txt"); 12 f2 = new File("file/part2.txt"); 13 f3 = new File("file/part3.txt"); 14 Scanner sc = new Scanner(x); 15 PrintWriter pw1 = new PrintWriter(f1); 16 PrintWriter pw2 = new PrintWriter(f2); 17 PrintWriter pw3 = new PrintWriter(f3); 18 pw1.println(sc.nextLine()); 19 pw2.println(sc.nextLine()); 20 while(sc.hasNextLine()) 21 { 22 pw3.println(sc.nextLine()); 23 } 24 pw1.close(); 25 pw2.close(); 26 pw3.close(); 27 sc.close(); 28 } 29 public void FileGroup(File []x,int num) throws FileNotFoundException{ 30 File file = new File("file/AddTo.txt"); 31 PrintWriter pw = new PrintWriter(file); 32 for(int i=0;i<num;++i) 33 { 34 Scanner sc = new Scanner(x[i]); 35 while(sc.hasNextLine()) 36 { 37 pw.println(sc.nextLine()); 38 } 39 sc.close(); 40 } 41 pw.close(); 42 } 43 public static void main(String[] args) throws FileNotFoundException { 44 File f = new File("file/basic.txt"); 45 File []fs = new File[3]; 46 for(int i=0;i<3;++i) 47 fs[i] = new File("file/part"+(i+1)+".txt"); 48 TestZip tz = new TestZip(); 49 tz.FileFrozen(f); 50 tz.FileGroup(fs,3); 51 } 52 }
Part 6:计算文件夹的总大小的工具+实现文件加密功能
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package tempzerb; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 import java.nio.file.FileVisitResult; 7 import java.nio.file.Files; 8 import java.nio.file.Path; 9 import java.nio.file.Paths; 10 import java.nio.file.SimpleFileVisitor; 11 import java.nio.file.attribute.BasicFileAttributes; 12 import java.util.LinkedList; 13 import java.util.List; 14 import java.util.Random; 15 import java.util.Scanner; 16 17 class FilterFilesVisitor extends SimpleFileVisitor<Path> { 18 19 private List<String> result = new LinkedList<String>(); 20 21 private long Length = 0; 22 23 public long getLength() { 24 return Length; 25 } 26 public void setLength(long length) { 27 Length = length; 28 } 29 public FilterFilesVisitor(List<String> result) { 30 this.result = result; 31 Length = 0; 32 } 33 //查询以 ends 为结尾的文件 34 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { 35 Length = Length + file.toFile().length(); 36 return FileVisitResult.CONTINUE; 37 } 38 //查询以 ends 为结尾的文件 39 public FileVisitResult visitFileEndWith(Path file, BasicFileAttributes attrs,String ends) { 40 if (file.toString().endsWith(ends)) { 41 result.add(file.toString()); 42 } 43 Length = Length + file.toFile().length(); 44 return FileVisitResult.CONTINUE; 45 } 46 //查询包含 card 字符串的文件 47 public FileVisitResult visitFileContains(Path file, BasicFileAttributes attrs,String card) { 48 if (file.toString().contains(card)) { 49 result.add(file.toString()); 50 } 51 Length = Length + file.toFile().length(); 52 return FileVisitResult.CONTINUE; 53 } 54 //查询大小处于m和n之间的文件 55 public FileVisitResult visitFileContains(Path file, BasicFileAttributes attrs,long m,long n) { 56 if (file.toFile().length()>=m&&file.toFile().length()<=n) { 57 result.add(file.toString()); 58 } 59 Length = Length + file.toFile().length(); 60 return FileVisitResult.CONTINUE; 61 } 62 } 63 64 public class QTest { 65 public void test1(Path path) throws IOException{ 66 List<String> result = new LinkedList<String>(); 67 FilterFilesVisitor ffv = new FilterFilesVisitor(result); 68 Files.walkFileTree(path,ffv); 69 System.out.println("总大小为: " + ffv.getLength()); 70 } 71 public void test2(File x) throws IOException{ 72 //加密文件 73 File enFile = new File("file/enfile.txt"); 74 //解密文件 75 File untiFile = new File("file/untifile.txt"); 76 if(enFile.exists()) 77 enFile.delete(); 78 if(untiFile.exists()) 79 untiFile.delete(); 80 enFile.createNewFile(); 81 untiFile.createNewFile(); 82 Scanner sc = new Scanner(x); 83 PrintWriter pw = new PrintWriter(enFile); 84 PrintWriter pws = new PrintWriter(untiFile); 85 Random random = new Random(System.currentTimeMillis()); 86 int c = random.nextInt(10); 87 pws.append((char)c); 88 while(sc.hasNext()) 89 { 90 String str = sc.next(); 91 char []cha = str.toCharArray(); 92 for(int i=0;i<cha.length;++i) 93 pw.append((char)(cha[i]-c)); 94 pw.append(' '); 95 } 96 pws.close(); 97 sc.close(); 98 pw.close(); 99 } 100 public void test3(Path path){ 101 102 } 103 public static void main(String[] args) throws IOException { 104 QTest q = new QTest(); 105 Path path = Paths.get("file"); 106 q.test1(path); 107 q.test2(new File("file/Mort.jsp")); 108 q.test3(path); 109 } 110 }
运行截图:
说明:我的文件加密就是文件的字符都减去同一个随机值...并把这个随机值读到某一个文件当中去,这个文件就是解码文件,而减去随机值的字符们进而构成了我们无法直接识别、读取的伪乱码,这就是加密文件了,这个加密文件的保存内容,你真的看不懂,难道你看的出来上边的图片内容实际上是"Hello World"吗?只有通过调用解码文件的特殊字符,进而完成对加密文件的解码,才能得到真正“可读”的文件!而读取文件总大小的话,就设一个值,遍历文件就好了,没遍历一个文件,就加上它的长度!最终得到的大小就是文件夹里的所有文件的大小。至于文件的分割其实就是将文件读取到的数据,写入不同的两个文件里边去。