Advertisement
ibragimova_mariam

Поиск файлов

Dec 1st, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3. import java.util.Stack;
  4. import java.util.zip.CRC32;
  5. import java.util.zip.CheckedInputStream;
  6.  
  7. public class Main {
  8. private static long calculateCRC32(File file) {
  9. long checksum = -1;
  10.  
  11. try {
  12. CheckedInputStream cis = null;
  13.  
  14. try {
  15. cis = new CheckedInputStream(new FileInputStream(file), new CRC32());
  16. } catch (FileNotFoundException e) {
  17. System.err.println("Файл не найден");
  18. System.exit(1);
  19. }
  20.  
  21. byte[] buf = new byte[128];
  22. while(cis.read(buf) >= 0);
  23.  
  24. checksum = cis.getChecksum().getValue();
  25. } catch (IOException e) {
  26. System.out.println("Ошибка чтения файла");
  27. e.printStackTrace();
  28. System.exit(1);
  29. }
  30.  
  31. return checksum;
  32. }
  33.  
  34. public static void main(String[] args) {
  35. Scanner in = new Scanner(System.in);
  36.  
  37. System.out.println("Введите директорию поиска:");
  38. String folder = in.nextLine();
  39.  
  40. System.out.println("Введите путь к файлу, который нужно найти:");
  41. String file = in.nextLine();
  42.  
  43. File dir = new File(folder);
  44. File source = new File(file);
  45.  
  46. if (!source.exists() || !source.canRead() || source.isDirectory()) {
  47. System.out.println("Невозможно открыть файл – файл не доступен для чтения.");
  48. } else if (!dir.exists() || !dir.canRead() || dir.isFile()) {
  49. System.out.println("Невозможно открыть папку – папка не доступна для чтения.");
  50. } else {
  51. Stack<File> stack = new Stack<>();
  52. stack.push(dir);
  53.  
  54. long key = calculateCRC32(source);
  55.  
  56. while (!stack.empty()) {
  57. File cur = stack.pop();
  58.  
  59. if (cur.canRead()) {
  60. for (File f : cur.listFiles()) {
  61. if (f.canRead()) {
  62. if (f.isFile()) {
  63. if (key == calculateCRC32(f)) {
  64. System.out.println("Найдено совпадение: " + f.getAbsolutePath());
  65. }
  66. } else {
  67. stack.push(f);
  68. }
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement