kristina7

НП - File System

Jan 13th, 2019
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.34 KB | None | 0 0
  1. /*
  2. Да се имплементира класа FileSystem за едноставен податочен систем. За вашиот податочен систем треба да имплементирате сопствена класа за датотека File со податоци за име (String), големина (Integer) и време на креирање (LocalDateTime) Класата треба да ги овозможува следните функционалности:
  3.  
  4. public void addFile(char folder, String name, int size, LocalDateTime createdAt) - метод за додавање нова датотека File во фолдер со даденото име (името на фолдерот е еден знак, може да биде . или голема буква)
  5. public List<File> findAllHiddenFilesWithSizeLessThen(int size) - враќа листа на сите скриени датотеки (тоа се датотеки чие што име започнува со знакот за точка .) со големина помала од size.
  6. public int totalSizeOfFilesFromFolders(List<Character> folders) - враќа вкупна големина на сите датотеки кои се наоѓаат во фолдерите кои се зададени во листата folders
  7. public Map<Integer, Set<File>> byYear() - враќа мапа Map во која за датотеките се групирани според годината на креирање.
  8. public Map<String, Long> sizeByMonthAndDay() - враќа мапа Map во која за секој месец и ден (независно од годината) се пресметува вкупната големина на сите датотеки креирани во тој месец и тој ден. Месецот се добива со повик на методот getMonth(), а денот getDayOfMonth().
  9. Датотеките во секој фолдер се подредени според датумот на креирање во растечки редослед, потоа според името лексикографски и на крај според големината. Да се имплементира ваков компаратор во самата класа File. Исто така да се имплементира и toString репрезентација во следниот формат:
  10.  
  11. %-10[name] %5[size]B %[createdAt]
  12. */
  13.  
  14. import java.time.LocalDateTime;
  15. import java.util.*;
  16. import java.util.function.Predicate;
  17. import java.util.stream.Collectors;
  18.  
  19. class File implements Comparable<File> {
  20.     String name;
  21.     Integer size;
  22.     LocalDateTime createdAt;
  23.  
  24.     public File(String name, Integer size, LocalDateTime createdAt) {
  25.         this.name = name;
  26.         this.size = size;
  27.         this.createdAt = createdAt;
  28.     }
  29.  
  30.     public String getName() {
  31.         return name;
  32.     }
  33.  
  34.     public Integer getSize() {
  35.         return size;
  36.     }
  37.  
  38.     public LocalDateTime getCreatedAt() {
  39.         return createdAt;
  40.     }
  41.  
  42.     public String monthAndDay() {
  43.         return createdAt.getMonth() + "-" + createdAt.getDayOfMonth();
  44.     }
  45.  
  46.     @Override
  47.     public int compareTo(File f) {
  48.         return Comparator.comparing(File::getCreatedAt).thenComparing(File::getName).thenComparing(File::getSize)
  49.                 .compare(this, f);
  50.     }
  51.  
  52.     @Override
  53.     public String toString() {
  54.         return String.format("%-10s %5dB %s", name, size, createdAt);
  55.     }
  56. }
  57.  
  58. class FileSystem {
  59.     Map<Character, Set<File>> files;
  60.  
  61.     public FileSystem() {
  62.         files = new HashMap<>();
  63.     }
  64.  
  65.     public void addFile(char folder, String name, int size, LocalDateTime createdAt) {
  66.         files.computeIfAbsent(folder, key -> new TreeSet<>());
  67.         files.get(folder).add(new File(name, size, createdAt));
  68.     }
  69.  
  70.     public List<File> findAllHiddenFilesWithSizeLessThen(int size) {
  71.         Predicate<File> isOk = file -> file.name.startsWith(".") && file.size<size;
  72.         return files.values().stream().flatMap(file -> file.stream()).filter(isOk)
  73.                 .collect(Collectors.toList());
  74.     }
  75.  
  76.     public int totalSizeOfFilesFromFolders(List<Character> folders) {
  77.         return folders.stream().mapToInt(folder -> files.get(folder).stream().mapToInt(File::getSize).sum()).sum();
  78.     }
  79.  
  80.     public Map<Integer, Set<File>> byYear() {
  81.         return files.values().stream().flatMap(file -> file.stream())
  82.                 .collect(Collectors.groupingBy(file -> file.createdAt.getYear(), Collectors.toSet()));
  83.     }
  84.  
  85.     public Map<String, Long> sizeByMonthAndDay() {
  86.         return files.values().stream().flatMap(file -> file.stream())
  87.                 .collect(Collectors.groupingBy(File::monthAndDay, Collectors.summingLong(File::getSize)));
  88.     }
  89. }
  90.  
  91. public class FileSystemTest {
  92.     public static void main(String[] args) {
  93.         FileSystem fileSystem = new FileSystem();
  94.         Scanner scanner = new Scanner(System.in);
  95.         int n = scanner.nextInt();
  96.         scanner.nextLine();
  97.         for (int i = 0; i < n; i++) {
  98.             String line = scanner.nextLine();
  99.             String[] parts = line.split(":");
  100.             fileSystem.addFile(parts[0].charAt(0), parts[1], Integer.parseInt(parts[2]),
  101.                     LocalDateTime.of(2016, 12, 29, 0, 0, 0).minusDays(Integer.parseInt(parts[3])));
  102.         }
  103.         int action = scanner.nextInt();
  104.         if (action == 0) {
  105.             scanner.nextLine();
  106.             int size = scanner.nextInt();
  107.             System.out.println("== Find all hidden files with size less then " + size);
  108.             List<File> files = fileSystem.findAllHiddenFilesWithSizeLessThen(size);
  109.             files.forEach(System.out::println);
  110.         } else if (action == 1) {
  111.             scanner.nextLine();
  112.             String[] parts = scanner.nextLine().split(":");
  113.             System.out.println("== Total size of files from folders: " + Arrays.toString(parts));
  114.             int totalSize = fileSystem.totalSizeOfFilesFromFolders(
  115.                     Arrays.stream(parts).map(s -> s.charAt(0)).collect(Collectors.toList()));
  116.             System.out.println(totalSize);
  117.         } else if (action == 2) {
  118.             System.out.println("== Files by year");
  119.             Map<Integer, Set<File>> byYear = fileSystem.byYear();
  120.             byYear.keySet().stream().sorted().forEach(key -> {
  121.                 System.out.printf("Year: %d\n", key);
  122.                 Set<File> files = byYear.get(key);
  123.                 files.stream().sorted().forEach(System.out::println);
  124.             });
  125.         } else if (action == 3) {
  126.             System.out.println("== Size by month and day");
  127.             Map<String, Long> byMonthAndDay = fileSystem.sizeByMonthAndDay();
  128.             byMonthAndDay.keySet().stream().sorted()
  129.                     .forEach(key -> System.out.printf("%s -> %d\n", key, byMonthAndDay.get(key)));
  130.         }
  131.         scanner.close();
  132.     }
  133. }
Advertisement
Add Comment
Please, Sign In to add comment