[AI writes code for me, fishing at work is not a dream] The process of training ChatGPT is fully recorded, let it help me write the program❗

Recently, I found that the disk space is seriously insufficient, and pop-up windows reminded me:

Think about which folder takes up the most space, so that you can delete and clean it in a targeted manner. However, the Windows system does not have a tool to check the size of the folder. You can only place the mouse on a certain folder and wait for the prompt:

The AI ​​era is coming, let ChatGPT help me write a program: calculate and sort the size of all folders in the specified folder.

first edition

So, I asked ChatGPT:

The full code is this:

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class FolderSizeCalculator {
    
    
    public static void main(String[] args) {
    
    
        // 指定文件夹路径
        String folderPath = "/path/to/folder";

        // 获取文件夹列表
        File folder = new File(folderPath);
        File[] folderList = folder.listFiles(File::isDirectory);

        // 计算每个文件夹的大小并存储到ArrayList中
        ArrayList<Folder> folders = new ArrayList<>();
        for (File f : folderList) {
    
    
            long size = getFolderSize(f);
            Folder folderObj = new Folder(f.getName(), size);
            folders.add(folderObj);
        }

        // 根据文件夹大小进行排序
        Collections.sort(folders, Comparator.comparingLong(Folder::getSize));

        // 输出结果
        for (Folder f : folders) {
    
    
            System.out.println(f.getName() + " - " + formatSize(f.getSize()));
        }
    }

    // 递归计算文件夹大小
    public static long getFolderSize(File folder) {
    
    
        long size = 0;
        File[] fileList = folder.listFiles();
        if (fileList != null) {
    
    
            for (File f : fileList) {
    
    
                if (f.isFile()) {
    
    
                    size += f.length();
                } else {
    
    
                    size += getFolderSize(f);
                }
            }
        }
        return size;
    }

    // 格式化文件大小
    public static String formatSize(long size) {
    
    
        String[] units = {
    
    "B", "KB", "MB", "GB", "TB"};
        int i = 0;
        double s = size;
        while (s >= 1024 && i < units.length - 1) {
    
    
            s /= 1024;
            i++;
        }
        return String.format("%.2f %s", s, units[i]);
    }
}

// 文件夹类
class Folder {
    
    
    private String name;
    private long size;

    public Folder(String name, long size) {
    
    
        this.name = name;
        this.size = size;
    }

    public String getName() {
    
    
        return name;
    }

    public long getSize() {
    
    
        return size;
    }
}

Use Filea class to get all subfolders in a specified folder, then use a recursive function getFolderSizeto calculate the size of each folder, and finally store the result into one ArrayList. The program uses methods to sort Collections.sortfolders by size and methods to format file sizes and output the results.ArrayListformatSize

Modify the path of the specified folder to run, and the effect is not bad:

社 - 646.13 KB
学 - 141.15 MB
猫 - 587.99 MB
万 - 1.52 GB

The only flaw is that the sorting is from small to large, so make a slight modification and put

// 根据文件夹大小进行排序
Collections.sort(folders, Comparator.comparingLong(Folder::getSize));

change into:

// 根据文件夹大小进行排序
Collections.sort(folders, (f1, f2) -> Long.compare(f2.getSize(), f1.getSize()));

Run it to see the effect:

万 - 1.52 GB
猫 - 587.99 MB
学 - 141.15 MB
社 - 646.13 KB

evolution

Every time you modify the folder path that needs to be calculated, you need to modify the code and run it again, which is very inconvenient. I thought of Swing, which can interact with the UI. So, I asked ChatGPT again:

The complete code is as follows:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class FolderSizeSorter extends JFrame {
    
    
    private JLabel directoryLabel;
    private JTextField directoryTextField;
    private JButton calculateButton;
    private JTextArea resultTextArea;
    
    public FolderSizeSorter() {
    
    
        super("Folder Size Sorter");
        
        // set up UI components
        directoryLabel = new JLabel("Directory:");
        directoryTextField = new JTextField(20);
        calculateButton = new JButton("Calculate");
        resultTextArea = new JTextArea(20, 40);
        JScrollPane scrollPane = new JScrollPane(resultTextArea);
        
        // set up layout
        JPanel inputPanel = new JPanel();
        inputPanel.add(directoryLabel);
        inputPanel.add(directoryTextField);
        inputPanel.add(calculateButton);
        add(inputPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        
        // set up event listeners
        calculateButton.addActionListener(new ActionListener() {
    
    
            public void actionPerformed(ActionEvent e) {
    
    
                calculateFolderSizes();
            }
        });
        
        // set up window properties
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 400);
        setVisible(true);
    }
    
    private void calculateFolderSizes() {
    
    
        String directoryPath = directoryTextField.getText();
        File directory = new File(directoryPath);
        if (!directory.isDirectory()) {
    
    
            JOptionPane.showMessageDialog(this, "Please enter a valid directory path.");
            return;
        }
        
        Map<File, Long> folderSizes = new HashMap<>();
        calculateFolderSizesRecursive(directory, folderSizes);
        
        List<Map.Entry<File, Long>> folderSizesList = new ArrayList<>(folderSizes.entrySet());
        Collections.sort(folderSizesList, new Comparator<Map.Entry<File, Long>>() {
    
    
            public int compare(Map.Entry<File, Long> o1, Map.Entry<File, Long> o2) {
    
    
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        
        resultTextArea.setText("");
        for (Map.Entry<File, Long> folderSize : folderSizesList) {
    
    
            resultTextArea.append(folderSize.getKey().getPath() + " - " + formatSize(folderSize.getValue()) + "\n");
        }
    }
    
    private void calculateFolderSizesRecursive(File folder, Map<File, Long> folderSizes) {
    
    
        File[] files = folder.listFiles();
        if (files == null) {
    
    
            return;
        }
        long folderSize = 0;
        for (File file : files) {
    
    
            if (file.isDirectory()) {
    
    
                calculateFolderSizesRecursive(file, folderSizes);
                folderSize += folderSizes.get(file);
            } else {
    
    
                folderSize += file.length();
            }
        }
        folderSizes.put(folder, folderSize);
    }
    
    private String formatSize(long size) {
    
    
        String[] units = {
    
    "B", "KB", "MB", "GB", "TB"};
        int unitIndex = 0;
        double dSize = size;
        while (dSize >= 1024 && unitIndex < units.length - 1) {
    
    
            dSize /= 1024;
            unitIndex++;
        }
        return String.format("%.2f %s", dSize, units[unitIndex]);
    }
    
    public static void main(String[] args) {
    
    
        new FolderSizeSorter();
    }
}

Create a GUI window, including a label, a text box, and a button. Enter the path of the folder in the text box and click "Calculate". The effect is as follows:

re-evolution

In the process of using, there is a new problem: I saw that a certain folder is relatively large, and I want to check the size of the folders under this folder, and I have to manually copy and paste the folder path to recalculate, which is not easy to operate. very convenient. So, I asked ChatGPT again:

The complete code is as follows:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class FolderSizeCalculator extends JFrame {
    
    
    
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JButton btnSelectFolder;
    private JTree tree;
    private DefaultTreeModel treeModel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
    
    
        EventQueue.invokeLater(new Runnable() {
    
    
            public void run() {
    
    
                try {
    
    
                    FolderSizeCalculator frame = new FolderSizeCalculator();
                    frame.setVisible(true);
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public FolderSizeCalculator() {
    
    
        setTitle("Folder Size Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        btnSelectFolder = new JButton("Select Folder");
        btnSelectFolder.addActionListener(new ActionListener() {
    
    
            public void actionPerformed(ActionEvent e) {
    
    
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = fileChooser.showOpenDialog(FolderSizeCalculator.this);
                if (result == JFileChooser.APPROVE_OPTION) {
    
    
                    File folder = fileChooser.getSelectedFile();
                    DefaultMutableTreeNode root = new DefaultMutableTreeNode(folder.getName());
                    treeModel = new DefaultTreeModel(root);
                    tree.setModel(treeModel);
                    calculateFolderSize(folder, root);
                    tree.expandRow(0);
                }
            }
        });
        contentPane.add(btnSelectFolder, BorderLayout.NORTH);

        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        tree = new JTree();
        scrollPane.setViewportView(tree);
    }

    private void calculateFolderSize(File folder, DefaultMutableTreeNode node) {
    
    
        long size = 0;
        List<File> subfolders = new ArrayList<>();
        for (File file : folder.listFiles()) {
    
    
            if (file.isDirectory()) {
    
    
                subfolders.add(file);
            } else {
    
    
                size += file.length();
            }
        }
        Collections.sort(subfolders);
        for (File subfolder : subfolders) {
    
    
            DefaultMutableTreeNode subnode = new DefaultMutableTreeNode(subfolder.getName());
            node.add(subnode);
            calculateFolderSize(subfolder, subnode);
        }
        node.setUserObject(node.getUserObject() + " (" + humanReadableByteCount(size, false) + ")");
    }

    private String humanReadableByteCount(long bytes, boolean si) {
    
    
        int unit = si ? 1000 : 1024;
        if (bytes < unit)
            return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
	    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
	    return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
	}
}

JFrameIn this program, a class that inherits from is created FolderSizeCalculatorand a user interface is created in it.

We can select the folder to calculate the size by clicking the "Select Folder" button. Once the user selects a folder, the program will calculate the size of all folders in this folder and display the results in a tree structure.

The way to calculate the size of a folder is that calculateFolderSizeit uses recursion to walk through the folder and its subfolders, calculating their sizes. This method adds each subfolder as a node to the tree and adds the folder size to the node name.

humanReadableByteCountis a helper method for converting the file size from bytes to a human readable format (e.g. MB, GB, etc.).

Run it to see the effect:

Found the problem, the size of the subfolder is larger than that of the parent folder. After reading the code carefully, I found that the calculateFolderSizesize of the file is accumulated in the method, but the size of the subfolder is not accumulated. So, I asked ChatGPT again:

ChatGPT adds a calculateTotalSizemethod:

private long calculateTotalSize(File folder) {
    
    
    long totalSize = 0;
    if (folder.isDirectory()) {
    
    
        for (File file : folder.listFiles()) {
    
    
            if (file.isDirectory()) {
    
    
                totalSize += calculateTotalSize(file);
            } else {
    
    
                totalSize += file.length();
            }
        }
    } else {
    
    
        totalSize = folder.length();
    }
    return totalSize;
}

In the method, first check if the passed folder is a folder type. If it is a folder, iterate through all its children, and if the child is a folder, call the method recursively to calculate its size; if the child is a file, add its size to the total size. If the passed folder is a file, its size is returned directly. Ultimately, the method returns the total size.

The above method is integrated into the original method to calculate the sum of the sizes of all files and folders under the folder. Here is the modified sample code:

private void calculateFolderSize(File folder, DefaultMutableTreeNode node) {
    
    
    long size = calculateTotalSize(folder);
    List<File> subfolders = new ArrayList<>();
    for (File file : folder.listFiles()) {
    
    
        if (file.isDirectory()) {
    
    
            subfolders.add(file);
        }
    }
    Collections.sort(subfolders);
    for (File subfolder : subfolders) {
    
    
        DefaultMutableTreeNode subnode = new DefaultMutableTreeNode(subfolder.getName());
        node.add(subnode);
        calculateFolderSize(subfolder, subnode);
    }
    node.setUserObject(node.getUserObject() + " (" + humanReadableByteCount(size, false) + ")");
}

We can find that the performance of the modified code of ChatGPT is not very good, because calculateFolderSizethe method is a recursive method, and in this recursive method, it is necessary to recurse each folder again.

We can complete the entire calculation process in one recursion. So, I asked ChatGPT again:

Unfortunately, although I have labeled ChatGPT an excellent hat, the answer is still not ideal.

I can only do it myself, and calculateFolderSizemodify the method to:

private long calculateFolderSize(File folder, DefaultMutableTreeNode node) {
    
    
    long size = 0;
    Map<DefaultMutableTreeNode, Long> nodeMap = new HashMap<>();
    for (File file : folder.listFiles()) {
    
    
        if (file.isDirectory()) {
    
    
            DefaultMutableTreeNode subnode = new DefaultMutableTreeNode(file.getName());
            long subSize = calculateFolderSize(file, subnode);
            nodeMap.put(subnode, subSize);
            size += subSize;
        } else {
    
    
            size += file.length();
        }
    }
    List<Entry<DefaultMutableTreeNode, Long>> nodes = new ArrayList<>(nodeMap.entrySet());
    Collections.sort(nodes, (o1,o2)-> o2.getValue().compareTo(o1.getValue()));
    for (Map.Entry<DefaultMutableTreeNode, Long> entry : nodes) {
    
    
        node.add(entry.getKey());
    }
    node.setUserObject(node.getUserObject() + " (" + humanReadableByteCount(size, false) + ")");
    return size;
}

Run it to see the effect:

end

Since ChatGPT and other AI technologies have swept the world, many people have begun to worry: Will I be replaced by AI? Although AI has demonstrated amazing capabilities in many fields, there are still many difficulties to overcome in order to completely replace humans.

In this article, even though the AI ​​currently shows a high level of skill, it still needs my improvement and optimization to complete the tasks I have provided. AI can be seen as a tool to help me solve some complex problems and improve work efficiency.

Therefore, instead of AI, you will be replaced by those who can use AI.

Attachment: final complete code

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class FolderSizeCalculator extends JFrame {
    
    

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JButton btnSelectFolder;
    private JTree tree;
    private DefaultTreeModel treeModel;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
    
    
        EventQueue.invokeLater(() -> {
    
    
            try {
    
    
                FolderSizeCalculator frame = new FolderSizeCalculator();
                frame.setVisible(true);
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        });
    }

    /**
     * Create the frame.
     */
    public FolderSizeCalculator() {
    
    
        setTitle("Folder Size Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        btnSelectFolder = new JButton("Select Folder");
        btnSelectFolder.addActionListener(new ActionListener() {
    
    
            @Override
            public void actionPerformed(ActionEvent e) {
    
    
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = fileChooser.showOpenDialog(FolderSizeCalculator.this);
                if (result == JFileChooser.APPROVE_OPTION) {
    
    
                    File folder = fileChooser.getSelectedFile();
                    DefaultMutableTreeNode root = new DefaultMutableTreeNode(folder.getName());
                    treeModel = new DefaultTreeModel(root);
                    tree.setModel(treeModel);
                    calculateFolderSize(folder, root);
                    tree.expandRow(0);
                }
            }
        });
        contentPane.add(btnSelectFolder, BorderLayout.NORTH);

        JScrollPane scrollPane = new JScrollPane();
        contentPane.add(scrollPane, BorderLayout.CENTER);

        tree = new JTree();
        scrollPane.setViewportView(tree);
    }

    private long calculateFolderSize(File folder, DefaultMutableTreeNode node) {
    
    
        long size = 0;
        Map<DefaultMutableTreeNode, Long> nodeMap = new HashMap<>();
        for (File file : folder.listFiles()) {
    
    
            if (file.isDirectory()) {
    
    
                DefaultMutableTreeNode subnode = new DefaultMutableTreeNode(file.getName());
                long subSize = calculateFolderSize(file, subnode);
                nodeMap.put(subnode, subSize);
                size += subSize;
            } else {
    
    
                size += file.length();
            }
        }
        List<Entry<DefaultMutableTreeNode, Long>> nodes = new ArrayList<>(nodeMap.entrySet());
        nodes.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
        for (Map.Entry<DefaultMutableTreeNode, Long> entry : nodes) {
    
    
            node.add(entry.getKey());
        }
        node.setUserObject(node.getUserObject() + " (" + humanReadableByteCount(size, false) + ")");
        return size;
    }

    private String humanReadableByteCount(long bytes, boolean si) {
    
    
        int unit = si ? 1000 : 1024;
        if (bytes < unit) {
    
    
            return bytes + " B";
        }
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

}

Guess you like

Origin blog.csdn.net/heihaozi/article/details/130335560