swen922

SearchFileVisitor

Aug 19th, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. package com.javarush.task.task31.task3111;
  2.  
  3.  
  4. import java.io.IOException;
  5. import java.nio.file.FileVisitResult;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.SimpleFileVisitor;
  9. import java.nio.file.attribute.BasicFileAttributes;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12.  
  13. public class SearchFileVisitor extends SimpleFileVisitor<Path> {
  14.  
  15.     private String partOfName;
  16.     private String partOfContent;
  17.     private int minSize;
  18.     private int maxSize;
  19.     private List<Path> foundFiles = new ArrayList<>();
  20.  
  21.     private boolean needPartOfName = false;
  22.     private boolean needPartOfContent = false;
  23.     private boolean needMinSize = false;
  24.     private boolean needMaxSize = false;
  25.  
  26.  
  27.     public void setPartOfName(String partOfName) {
  28.         this.partOfName = partOfName;
  29.         this.needPartOfName = true;
  30.     }
  31.     public void setPartOfContent(String partOfContent) {
  32.         this.partOfContent = partOfContent;
  33.         this.needPartOfContent = true;
  34.     }
  35.     public void setMinSize(int minSize) {
  36.         this.minSize = minSize;
  37.         this.needMinSize = true;
  38.     }
  39.     public void setMaxSize(int maxSize) {
  40.         this.maxSize = maxSize;
  41.         this.needMaxSize = true;
  42.     }
  43.  
  44.     public List<Path> getFoundFiles() {
  45.         return foundFiles;
  46.     }
  47.  
  48.     @Override
  49.     public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  50.  
  51.         byte[] content = Files.readAllBytes(file); // размер файла: content.length
  52.  
  53.         if(needPartOfName && !(file.getFileName().toString().contains(partOfName))) {
  54.             return FileVisitResult.CONTINUE;
  55.         }
  56.  
  57.         if(needPartOfContent) {
  58.             String s = new String(content);
  59.             if (!s.contains(partOfContent)) {
  60.                 return FileVisitResult.CONTINUE;
  61.             }
  62.         }
  63.  
  64.         if (needMinSize && (content.length <= minSize)) {
  65.             return FileVisitResult.CONTINUE;
  66.         }
  67.  
  68.         if (needMaxSize && (content.length >= maxSize)) {
  69.             return FileVisitResult.CONTINUE;
  70.         }
  71.  
  72.         foundFiles.add(file);
  73.  
  74.         return super.visitFile(file, attrs);
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment