summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/util/FilesystemUtil.java
blob: f245cffbb5fd2024551fd1e5828ae14dd2c0d245 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.keuin.kbackupfabric.util;

import java.io.File;
import java.io.IOException;

import static org.apache.commons.io.FileUtils.forceDelete;

public class FilesystemUtil {

    /**
     * Get file sizes in bytes.
     * @param parentDirectory path to specific file.
     * @param fileName file name.
     * @return bytes. If failed, return -1.
     */
    public static long getFileSizeBytes(String parentDirectory, String fileName) {
        long fileSize = -1;
        try{
            File backupZipFile = new File(parentDirectory, fileName);
            fileSize = backupZipFile.length();
        } catch (SecurityException ignored){
        }
        return fileSize;
    }

    public static long getFileSizeBytes(String filePath) {
        long fileSize = -1;
        try {
            File backupZipFile = new File(filePath);
            fileSize = backupZipFile.length();
        } catch (SecurityException ignored) {
        }
        return fileSize;
    }

    public static boolean forceDeleteDirectory(File levelDirFile) throws IOException {
        int failedCounter = 0;
        final int MAX_RETRY_TIMES = 20;
        IOException exception = null;
        while (failedCounter < MAX_RETRY_TIMES) {
            System.gc();
            if (!levelDirFile.delete() && levelDirFile.exists()) {
                System.gc();
                try {
                    forceDelete(levelDirFile); // Try to force delete.
                } catch (IOException e) {
                    exception = e;
                }
            }
            if (!levelDirFile.exists())
                break;
            ++failedCounter;
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {
            }
        }
        if (exception != null)
            throw exception;
        if (levelDirFile.exists()) {
            PrintUtil.error(String.format("Cannot restore: failed to delete old level %s .", levelDirFile.getName()));
            return false;
        }
        return true;
    }

}