Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.*;
- import java.nio.file.*;
- import java.nio.file.attribute.BasicFileAttributes;
- import java.util.*;
- public class Sync {
- static Path pathS;
- static Path pathD;
- static Set <Path> copyHashSet = new HashSet<Path>();
- static Set <Path> deleteHashSet = new HashSet<Path>();
- static boolean FileComparator (File fileA, File fileB) throws IOException {
- if (fileA.length() != fileB.length()) return false;
- else {
- BufferedInputStream inA = new BufferedInputStream(new FileInputStream(fileA));
- BufferedInputStream inB = new BufferedInputStream(new FileInputStream(fileB));
- char cA, cB;
- while (inA.available() > 0 && inB.available() > 0) {
- cA = (char) inA.read();
- cB = (char) inB.read();
- if (cA != cB) return false;
- }
- }
- return true;
- }
- static class CopyingFileVisitor extends SimpleFileVisitor<Path> {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException {
- copyHashSet.add(file.subpath(1, file.getNameCount())); // adding path
- //System.out.println(file.getNameCount()); // getNameCount returns number of folders in current path (starting from S )
- return FileVisitResult.CONTINUE;
- }
- }
- static class DeletingFileVisitor extends SimpleFileVisitor <Path> {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException {
- Path d = file.subpath(1, file.getNameCount());
- Path s = FileSystems.getDefault().getPath(pathS.toString() + "/" + d.toString());
- if (copyHashSet.contains(d) && FileComparator(s.toFile(), file.toFile())) copyHashSet.remove(d); // both files exist and equal
- else deleteHashSet.add(d); // both files exist but not equal or file does exist in D but not in S
- return FileVisitResult.CONTINUE;
- }
- }
- public static void main(String[] args) throws IOException {
- // write your code here
- File S = new File(args[0]);
- File D = new File(args[1]);
- pathS = S.toPath();
- pathD = D.toPath();
- Files.walkFileTree(pathS, new CopyingFileVisitor());
- Files.walkFileTree(pathD, new DeletingFileVisitor());
- if (copyHashSet.isEmpty() && deleteHashSet.isEmpty()) {
- System.out.println("IDENTICAL");
- } else {
- ArrayList <Path> copyList = new ArrayList<Path>(copyHashSet);
- ArrayList <Path> deleteList = new ArrayList<Path>(deleteHashSet);
- Collections.sort(copyList);
- Collections.sort(deleteList);
- for (int i = 0; i < deleteList.size(); i++) {
- System.out.println("DELETE " + deleteList.get(i));
- }
- for (int i = 0; i < copyList.size(); i++) {
- System.out.println("COPY " + copyList.get(i));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement