动手动脑一:
1.使用Files. walkFileTree()找出指定文件夹下所有大于指定大小(比如1M)的文件。这里我规定的是28672字节的文件
1 import java.io.IOException;
2 import java.nio.file.FileSystems;
3 import java.nio.file.FileVisitOption;
4 import java.nio.file.FileVisitResult;
5 import java.nio.file.FileVisitor;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.nio.file.Paths;
9 import java.nio.file.attribute.BasicFileAttributes;
10 import java.util.EnumSet;
11
12
13 public class Find1Mfile implements FileVisitor<Object> {
14 private final long accepted_size;
15 public Find1Mfile(String glob,long accepted_size) {
16 FileSystems.getDefault().getPathMatcher("glob:" +glob);
17 this.accepted_size=accepted_size;
18 }
19 void search(Path file) throws IOException {
20 long size = (Long) Files.getAttribute(file, "basic:size");
21 if(size ==accepted_size) {
22 System.out.println(file);
23 }
24
25 }
26 @Override
27 public FileVisitResult postVisitDirectory(Object dir, IOException exc)throws IOException {
28 return FileVisitResult.CONTINUE;
29 }
30 @Override
31 public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)throws IOException {
32 return FileVisitResult.CONTINUE;
33 }
34 @Override
35 public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)throws IOException {
36 search((Path) file);
37 return FileVisitResult.CONTINUE;
38 }
39 @Override
40 public FileVisitResult visitFileFailed(Object file, IOException exc)throws IOException {
41 return FileVisitResult.CONTINUE;
42 }
43
44
45 public static void main(String[] args) throws IOException{
46 String glob= "*.jpg"; // "glob:**/*.{java,txt,jpg}";
47 long size = 28672;
48 Path fileTree = Paths.get("D:/");
49 Find1Mfile walk=new Find1Mfile(glob, size);
50 EnumSet<FileVisitOption> opts=EnumSet.of(FileVisitOption.FOLLOW_LINKS);
51 System.out.println("D盘中大小等于28672字节的文件有");
52 Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
53 }
54 }
实现结果截图:

2.使用Files. walkFileTree()找出指定文件夹下所有扩展名为.txt和.java的文件。
1 import java.io.IOException;
2 import java.nio.file.FileSystems;
3 import java.nio.file.FileVisitResult;
4 import java.nio.file.Files;
5 import java.nio.file.Path;
6 import java.nio.file.PathMatcher;
7 import java.nio.file.Paths;
8 import java.nio.file.SimpleFileVisitor;
9 import java.nio.file.attribute.BasicFileAttributes;
10
11 public class FindTxtJava {
12
13 public static void main(String args[]) throws IOException {
14 String glob = "glob:**/*.{java,txt}";
15 String path = "D:/";
16 match(glob, path);
17 }
18
19 public static void match(String glob, String location) throws IOException {
20
21 final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher( glob);
22
23 Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
24
25 @Override
26 public FileVisitResult visitFile(Path path,
27 BasicFileAttributes attrs) throws IOException {
28 if (pathMatcher.matches(path)) {
29 System.out.println(path);
30 }
31 return FileVisitResult.CONTINUE;
32 }
33
34 @Override
35 public FileVisitResult visitFileFailed(Path file, IOException exc)
36 throws IOException {
37 return FileVisitResult.CONTINUE;
38 }
39 });
40 }
41
42 }
实现结果截图:

3.使用Files. walkFileTree()找出指定文件夹下所有包容指定字符串的txt文件
1 import java.io.IOException;
2 import java.io.*;
3 import java.nio.file.FileSystems;
4 import java.nio.file.FileVisitResult;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.nio.file.PathMatcher;
8 import java.nio.file.Paths;
9 import java.nio.file.SimpleFileVisitor;
10 import java.nio.file.attribute.BasicFileAttributes;
11
12 public class FileGlobNIO {
13
14 public static void main(String args[]) throws IOException {
15 String glob = "glob:**/*.txt";
16 String path = "D:\wenjian";
17 match(glob, path);
18 }
19
20 public static void match(String glob, String location) throws IOException {
21
22 final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher( glob);
23
24 Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
25
26 @Override
27 public FileVisitResult visitFile(Path path,
28 BasicFileAttributes attrs) throws IOException {
29 if (pathMatcher.matches(path)) {
30 BufferedReader reader =Files.newBufferedReader(path);//读取文件内的内容
31 String line=null;
32 while((line = reader.readLine())!=null) {
33 if(line.equals("account"))//若读取的内容等于“account"则输出文件名
34 {
35 System.out.println(path);
36 break;
37 }
38
39 }
40 }
41 return FileVisitResult.CONTINUE;
42 }
43
44 @Override
45 public FileVisitResult visitFileFailed(Path file, IOException exc)
46 throws IOException {
47 return FileVisitResult.CONTINUE;
48 }
49 });
50 }
51
52 }
实现结果截图:

动手动脑二:
1.请通过查询JDK文件和使用搜索引擎等方式,看懂此示例代码,并弄明白Watchable、WatchService等类型之间的关系,使用UML类图表示出这些类之间的关系?
WatchService
看作是文件监控器,通过操作系统原生文件系统来运行。
针对单点多appkey的情况,可以注册开启多个监控器。
每个监控器可看作是后台线程,通过监控文件发出的信号来实现监控。
WatchService 用来观察被注册了的对象所有的变化和事件
Watchable 被观察者,与WatchService结合使用, java.nio.file.Path 已经实现
WatchService 实例化:
WatchService watchService = FileSystems.getDefault().newWatchService();
利用 Path 实例化监控对象 Watchable
Path dir = Paths.get(path);
将 Path 注册到 WatchService 中//这里监控文件的 创建、修改、删除 但是这里返回的key里面的监控信息为空
WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
注意:监控池是静态的,只有当你主动去获取新的监控池时才会有更新的内容加入监控池。这就造成了系统接收到监控信息事件可能稍长的问题。
1,java.nio.file.WatchService文件系统监视服务的接口类,它的具体实现由监视服务提供者负责加载。
2,ava.nio.file.Watchable 实现了 java.nio.file.Watchable 的对象才能注册监视服务 WatchService。java.nio.file.Path实现了 watchable 接口,后文使用 Path 对象注册监视服务。
3,java.nio.file.WatchKey 该类代表着 Watchable 对象和监视服务 WatchService 的注册关系。WatchKey 在 Watchable 对象向 WatchService 注册的时候被创建。它是 Watchable 和 WatchService 之间的关联类。
课后作业:
1. 编写一个程序,指定一个文件夹,能自动计算出其总容量:
1 package class6;
2
3 import java.io.File;
4 import java.util.ArrayList;
5
6 public class Size {
7 static long size=0;
8 private static ArrayList<String> filelist=new ArrayList<String>();
9 public static void main(String[] args) {
10 Size s=new Size();
11 String filePath="F:\天梯赛";
12 s.getFiles(filePath);
13
14 }
15 //通过递归得到某一路径下所有的目录及文件
16 void getFiles(String filePath) {
17
18 File root=new File(filePath);
19 File[] files=root.listFiles();
20 for(File file:files) {
21 if(file.isDirectory()) {
22 getFiles(file.getAbsolutePath());
23 filelist.add(file.getAbsolutePath());
24 }else {
25 size+=file.getAbsolutePath().length();
26 }
27 }
28 System.out.println("大小是"+size);
29
30 }
31
32 }
实现结果截图:

2.编写一个文件加解密程序,通过命令行完成加解密工作
1 import java.io.File;
2 import java.io.InputStream;
3 import java.io.OutputStream;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6
7 public class FileCode {
8 private static final int numOfEncAndDec=0x99;//加密解密密钥
9 private static int dataOfFile=0;//文件字节内容
10
11 public static void main(String[] args) {
12 File srcFile=new File("d:\class6\poem.txt");//初始化文件
13 File encFile=new File("d:\class6\poem1.txt"); //加密文件
14 File decFile=new File("d:\class6\poem2.txt"); //解密文件
15
16 try {
17 EncFile(srcFile,encFile); //加密操作
18 DecFile(encFile,decFile);
19 }catch(Exception e) {
20 e.printStackTrace();
21 }
22 }
23 private static void EncFile(File srcFile,File encFile)throws Exception{
24 if(!srcFile.exists()) {
25 System.out.println("source file not exixt");
26 }
27 if(!encFile.exists()) {
28 System.out.println("encrypt file created");
29 encFile.createNewFile();//若无加密文件,新建一个加密文件
30 }
31 InputStream fis=new FileInputStream(srcFile);
32 OutputStream fos=new FileOutputStream(encFile);
33
34 while((dataOfFile=fis.read())>-1) {//当读到文件内容时
35 fos.write(dataOfFile^numOfEncAndDec);//将读出的内容加密后写入
36 }
37 fis.close();
38 fos.flush();
39 fos.close();
40 }
41 private static void DecFile(File encFile,File decFile)throws Exception{
42 if(!encFile.exists()) {
43 System.out.println("encrypt file not exixt");
44 }
45 if(!decFile.exists()) {
46 System.out.println("decrypt file created");
47 decFile.createNewFile();
48 }
49 InputStream fis=new FileInputStream(encFile);
50 OutputStream fos=new FileOutputStream(decFile);
51
52 while((dataOfFile=fis.read())>-1) {
53 fos.write(dataOfFile^numOfEncAndDec);
54 }
55 fis.close();
56 fos.flush();
57 fos.close();
58 }
59
60 }
实现结果截图:
未加密前:

加密后:

解密后:

3.编写一个文件分割工具,能把一个大文件分割成多个小的文件。并且能再次把它们合并起来得到完整的文件
1.分割文件:
1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6
7
8 public class CutFile {
9 public static void main(String[] args) {
10 //调用cutFile()函数 传人参数分别为 (原大文件,切割后存放的小文件的路径,切割规定的内存大小)
11 cutFile("D:\file\file.txt", "D:\file2",1024 * 1024 * 20);
12 }
13
14 private static void cutFile(String src, String endsrc, int num) {
15 FileInputStream fis = null;
16 File file = null;
17 try {
18 fis = new FileInputStream(src);
19 file = new File(src);
20 //创建规定大小的byte数组
21 byte[] b = new byte[num];
22 int len = 0;
23 //name为以后的小文件命名做准备
24 int name = 1;
25 //遍历将大文件读入byte数组中,当byte数组读满后写入对应的小文件中
26 while ((len = fis.read(b)) != -1) {
27 //分别找到原大文件的文件名和文件类型,为下面的小文件命名做准备
28 String name2 = file.getName();
29 int lastIndexOf = name2.lastIndexOf(".");
30 String substring = name2.substring(0, lastIndexOf);
31 String substring2 = name2.substring(lastIndexOf, name2.length());
32 FileOutputStream fos = new FileOutputStream(endsrc + "\\"+ substring + "-" + name + substring2);
33 //将byte数组写入对应的小文件中
34 fos.write(b, 0, len);
35 //结束资源
36 fos.close();
37 name++;
38 }
39 } catch (FileNotFoundException e) {
40 e.printStackTrace();
41 } catch (IOException e) {
42 e.printStackTrace();
43 } finally {
44 try {
45 if (fis != null) {
46 //结束资源
47 fis.close();
48 }
49 } catch (IOException e) {
50 e.printStackTrace();
51 }
52 }
53 }
54 }
实现结果截图:
未操作前:

分割后:

文件的集合:
1 package class6;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8
9 public class GotherFile {
10 public static void main(String[] args){
11 //调用togetherFile()函数合并小文件到大文件 参数列表分别为 (小文件所在的父文件夹路径,所合成的大文件的路径)
12 togetherFile("D:\file2","D:\file3\file.txt");
13 }
14 private static void togetherFile(String src, String endsrc){
15 FileOutputStream fos = null;
16 File file1 = null;
17 File file2 = null;
18 try {
19 file1 = new File(endsrc);
20 file2 = new File(src);
21 //获得大文件的存储路径的FileOutputStream对象
22 fos = new FileOutputStream(endsrc);
23 //循环遍历对应文件夹中的所有小文件
24 for(File file : file2.listFiles()){
25
26 FileInputStream fis = new FileInputStream(file.getAbsolutePath());
27
28 byte[] b = new byte[1024*1024];
29 int len = 0;
30 //将小文件读入byte数组,之后再将byte数组写入大文件中
31 while((len = fis.read(b)) != -1){
32 fos.write(b, 0, len);
33 }
34 //结束资源
35 fis.close();
36 }
37 } catch (FileNotFoundException e) {
38 e.printStackTrace();
39 } catch (IOException e) {
40 e.printStackTrace();
41 }finally{
42 try {
43 if(fos != null){
44 //结束资源
45 fos.close();
46 }
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50 }
51 }
52 }
操作前:

集合操作后:

