跳到主要內容

Find directories with specific size with Java. Recursive Function Demonstration.

The first function draft was generated by AI ChatGPT 3.5. But its comparative function was wrong and AI needed extra guidance to pinpoint that comparison of object in Java needs extra cares. Then its revised its recursive function. However the recursive function provided was still incorrect as it failed to count all the size of files and files inside the subfolders of a specific folder. Then I determined to finish it myself and here is my version.

The DirectorySizeChecker is a Java program that allows users to check the sizes of directories in their file system. The program takes in a directory path and an optional minimum size in megabytes as command line arguments, and outputs the paths and sizes of all directories that are equal to or larger than the specified size.

The program starts by setting a default minimum size of 100MB if no size argument is provided. It then checks if the correct number of arguments have been provided, and if the input directory exists and is indeed a directory.

The core functionality of the program is implemented in the listDirectories() method, which uses recursion to traverse the input directory and all its subdirectories, calculating the total size of each directory. When a directory is encountered, the method recursively calls itself on the subdirectory, and adds the size of the subdirectory to the size of the parent directory. If a file is encountered, its size is added to the size of the current directory.

It's worth noting that if a directory is encountered, the file.length() method will return 0, since directories do not have a size attribute like files do. Thus, the listDirectories() method keeps track of the total size of each directory by summing the sizes of all its files and subdirectories.

If a directory's size is greater than or equal to the minimum size, it is added to a list of directories. Finally, the program outputs the paths and sizes of all directories in the list. The sizes are converted from bytes to megabytes for readability.

Overall, the DirectorySizeChecker is a useful tool for quickly identifying large directories in a file system, which can help with disk space management and optimization.

 

You may download the code here too.

https://gist.github.com/edmundtt/b234df3865cefb87cbd588ac83977e5b


 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DirectorySizeChecker {

    public static void main(String[] args) {
    	long minimumSize = 100 * 1024 * 1024; // 100M
    	System.out.println("dirsizecheck ver 0.2");
    	System.out.println("args.length:"+args.length);
    	System.out.println("Example usage 1) java -jar dirsizecheck d:/newwkspace 100");
    	System.out.println("It means finding all directories with size is bigger than 100M");
    	System.out.println("Example usage 2) java -jar dirsizecheck d:/newwkspace");
    	System.out.println("It means finding all directories with size is bigger than the default which is 100M.");

    	if (args.length > 2 || args.length==0) {
            System.out.println("Usage 1: java dirsizecheck [directory_path] [size in M]");
            System.out.println("Usage 2: java dirsizecheck [directory_path]");
            System.out.println("         It will find directory size bigger than 100M");
            return;
        }

        String inputDirectoryPath = args[0];
        if(args.length==2)
        {
        	minimumSize = Long.parseLong(args[1]) * 1024 * 1024; // 100M
        }
        
        File inputDirectory = new File(inputDirectoryPath);
        if (!inputDirectory.exists() || !inputDirectory.isDirectory()) {
            System.out.println("Invalid directory path: " + inputDirectoryPath);
            return;
        }

        List<DirectorySize> directories = new ArrayList<DirectorySize>();
        listDirectories(inputDirectory, minimumSize, directories);

        for (DirectorySize directory : directories) {
            System.out.println(directory.path + "\t" + (long) (directory.size/1024/1024));
        }
    }

    private static long listDirectories(File directory, long minimumSize, List<DirectorySize> directories) {
        long directorySize = 0;

        File[] files = directory.listFiles();
        if (files == null) {
            return 0;
        }

        for (File file : files) {
        	long folder_size=0;
            if (file.isDirectory()) {
                folder_size=listDirectories(file, minimumSize, directories);
                //System.out.println(file.getAbsolutePath()+":"+file.length());
                directorySize += folder_size;
            } else {
                directorySize += file.length();
            }
        }

        if (directorySize >= minimumSize) {
            directories.add(new DirectorySize(directory.getAbsolutePath(), directorySize));
        }
        return directorySize;
    } //end function

    
    private static class DirectorySize {
        public final String path;
        public final long size;

        public DirectorySize(String path, long size) {
            this.path = path;
            this.size = size;
        }
    }

}

留言

這個網誌中的熱門文章

Setup Tomcat HTTPS (with JDK 8 to Java 15) in 2 mins

  Setup Tomcat 9 HTTPS/SSL To have a quick view, you may see the video(s): https://www.youtube.com/watch?v=WDGoF13vhZU 1. Generate Keystore I am using JDK 15 to generate the keystore. But the steps are similar with Tomcat 6 + openjdk 8(as I have tried it before writing this doc) Use “keytool” command to create a self-signed certificate. During the keystore creation process, you need to assign a password and fill in the certificate’s details. D:\apache-tomcat-9.0.38\conf>keytool -genkey -alias tomcatks -keyalg RSA -keystore D:\apache-tomcat-9.0.38\conf\tomcatks When enter the passwords during generation, please make sure the two passwords you entered are the SAME. This is the requirement of Tomcat. Here is the abstract from Tomcat installation  Finally, you will be prompted for the key password , which is the password specifically for this Certificate (as opposed to any other Certificates stored in the same keystore file). You MUST use the same password here as was used f...

全港乒乓球錦標賽 09 甲組賽事

今天換個輕鬆一點的題目,看看精彩的乒乓球 我在這裏介紹有個Channel有很清晰的乒乓球比賽片段,是全港乒乓球錦標賽甲組的賽事,其中有高澤禮在香港比賽的最新的片段 ,我相信這種場面很少有機會見到,因為,第一是業餘對專業,我在電視中都未看過,是認真比賽的那一種,不是國家隊奧運完結之後派冠軍來的表演賽,大家放軟手腳逗下逗下的那一種,可觀性高很多,第二,拍攝很有現場感,就算電視台都很少見到這樣的角度,就像親臨現場一樣。 雖然高禮澤貴為國際頂級球員,但落到這場地區賽事的時候都非常認真;雖然他技術高幾班,但認真程度從有球滴死對手時,球証看不清楚,而他正領先下,他都幫忙指証便可看出。 他是港隊中又有善又認真的專業球員,希望給年輕球員有認真對陣高水準球員的機會。 http://www.youtube.com/watch?v=nSo6Kg0vEus (這幾局可能是平均分數最接近的比賽) http://www.youtube.com/watch?v=LTJuYI906AI 還有很多其他攝錄質素很高的片段 謝嘉俊(港隊代表) vs 趙頌熙(港隊少年代表,在港有乒乓神童之稱,曾在11歲時贏得中國全國兒童賽冠軍) http://www.youtube.com/watch?v=zNEG2CzrDMI 謝嘉俊(港隊代表) vs 王德龍 09全港公開乒乓球單項錦標賽 Part 1 http://www.youtube.com/watch?v=OIeSo9V5V-0 趙頌熙(青少年港隊代表) 對 陳嘉耀 09全港公開乒乓球單項錦標賽 決勝局 Part 1 http://www.youtube.com/watch?v=jpaXjLL1bT4 陳文鋒 對 蔡鎮滔 2009全港公開乒乓球單項錦標賽 Part 2 http://www.youtube.com/watch?v=ZdcG8-I0buw&feature=channel_page 或者可以直接溜灠這個channel頻道 http://www.youtube.com/ppball

Files sharing problem between Windows 2003 server host and virtual machine

Regarding VMServer 1.08, when I copy files between a Windows 2003 host and a vm(no matter it is Windows XP or Windows 2003 Server), the following error prompted out arbitrarily, usually for copying large files. First I thought I had solved it by disabling the Jumbo frame and any kind of flow control in network card advance setting. It corrected the problem for most of the cases until I came across a situation to copy a 600MB file, the captioned error "network name is no longer available " prompted out after 10 to 20 seconds. It was not easy to find the solution as there are many cases, with different reasons, having the same symptom, thus I jot it down for a record. 1. Disable Jumbo frame, or any kind of flow control (try disabling Jumbo frame first) 2. Disable Denial of service attack in Windows 2003. Microsoft had acknowledged it has problem by itself in some cases. VMWare Server and "...network name is no longer available..." Did you ever receive following erro...