【第54题】输入、输出系列2-批量重命名,批量移动文件,批量删除tmp文件

举报
小虚竹 发表于 2022/05/13 23:08:40 2022/05/13
【摘要】 文章目录 零、前言一、题目描述-批量重命名1、题目2、解题思路3、代码详解 二、题目描述-批量移动文件1、题目2、解题思路3、代码详解4、多学一个知识点 三、题目描述-批量删除tmp文件1...

零、前言

​ 今天是学习 JAVA语言 打卡的第54天,每天我会提供一篇文章供群成员阅读( 不需要订阅付钱 ),读完文章之后,按解题思路,自己再实现一遍。在小虚竹JAVA社区 中对应的 【打卡贴】打卡,今天的任务就算完成了。

​ 因为大家都在一起学习同一篇文章,所以有什么问题都可以在群里问,群里的小伙伴可以迅速地帮到你,一个人可以走得很快,一群人可以走得很远,有一起学习交流的战友,是多么幸运的事情。

​ 学完后,自己写篇学习报告的博客,可以发布到小虚竹JAVA社区 ,供学弟学妹们参考。

​ 我的学习策略很简单,题海策略+ 费曼学习法。如果能把这100题都认认真真自己实现一遍,那意味着 JAVA语言 已经筑基成功了。后面的进阶学习,可以继续跟着我,一起走向架构师之路。

一、题目描述-批量重命名

1、题目

题目:在window操作系统中,支持对文件名重命名,但不支持批量重命名。

实现:做一个批量重命名的工具。

2、解题思路

创建一个类:RenameTool

使用RenameTool继承JFrame构建窗体

文件重命名的方法是使用File类中的renameTo()方法

3、代码详解

package com.xiaoxuzhu;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
/**
 * Description: 
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/3.1	    xiaoxuzhu		2022/5/3		    Create
 * </pre>
 * @date 2022/5/3
 */

public class RenameTool extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 9068225199875097200L;
    private JPanel contentPane;
    private JTextField selectTextField;
    private JTextField beforeCutTextField;
    private JTextField afterCutTextField;
    private JTextField beforeReplaceTextField;
    private JTextField afterReplaceTextField;
    private JTextField fileTypeTextField;
    private JCheckBox choiceCheckBox;
    private JButton renameButton;
    private File[] selectFiles;
    private JTextArea textArea;

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

    /**
     * Create the frame.
     */
    public RenameTool() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel controlPanel = new JPanel();
        contentPane.add(controlPanel, BorderLayout.NORTH);
        controlPanel.setLayout(new GridLayout(4, 1, 5, 5));

        JPanel selectPanel = new JPanel();
        controlPanel.add(selectPanel);

        JLabel selectLabel = new JLabel("选择的文件夹:");
        selectPanel.add(selectLabel);

        selectTextField = new JTextField();
        selectPanel.add(selectTextField);
        selectTextField.setColumns(18);

        JButton selectButton = new JButton("选择文件夹");
        selectButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_selectButton_actionPerformed(e);
            }
        });
        selectPanel.add(selectButton);

        JPanel cutPanel = new JPanel();
        controlPanel.add(cutPanel);

        JLabel beforeCutLabel = new JLabel("截取前字符:");
        cutPanel.add(beforeCutLabel);

        beforeCutTextField = new JTextField();
        cutPanel.add(beforeCutTextField);
        beforeCutTextField.setColumns(10);

        JLabel afterCutLabel = new JLabel("截取后字符:");
        cutPanel.add(afterCutLabel);

        afterCutTextField = new JTextField();
        cutPanel.add(afterCutTextField);
        afterCutTextField.setColumns(10);

        JPanel replacePanel = new JPanel();
        controlPanel.add(replacePanel);

        JLabel beforeReplaceLabel = new JLabel("替换前字符:");
        replacePanel.add(beforeReplaceLabel);

        beforeReplaceTextField = new JTextField();
        replacePanel.add(beforeReplaceTextField);
        beforeReplaceTextField.setColumns(10);

        JLabel afterReplaceLabel = new JLabel("替换后字符:");
        replacePanel.add(afterReplaceLabel);

        afterReplaceTextField = new JTextField();
        replacePanel.add(afterReplaceTextField);
        afterReplaceTextField.setColumns(10);

        JPanel otherPanel = new JPanel();
        controlPanel.add(otherPanel);

        JLabel fileTypeLabel = new JLabel("文件类型:");
        otherPanel.add(fileTypeLabel);

        fileTypeTextField = new JTextField();
        otherPanel.add(fileTypeTextField);
        fileTypeTextField.setColumns(17);

        choiceCheckBox = new JCheckBox("预览");
        choiceCheckBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                do_choiceCheckBox_itemStateChanged(e);
            }
        });
        otherPanel.add(choiceCheckBox);

        renameButton = new JButton("预览");
        renameButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_renameButton_actionPerformed(e);
            }
        });
        otherPanel.add(renameButton);

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

        textArea = new JTextArea();
        scrollPane.setViewportView(textArea);
    }

    protected void do_selectButton_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File directory = chooser.getSelectedFile();
            selectTextField.setText(directory.getAbsolutePath());
            selectFiles = directory.listFiles();
            for (File selectFile : selectFiles) {
                textArea.append(selectFile.getAbsolutePath() + "\n\r");
            }
        }
    }

    protected void do_choiceCheckBox_itemStateChanged(ItemEvent e) {
        if (choiceCheckBox.isSelected()) {
            choiceCheckBox.setText("重命名");
            renameButton.setText("重命名");
        } else {
            choiceCheckBox.setText("预览");
            renameButton.setText("预览");
        }
    }

    protected void do_renameButton_actionPerformed(ActionEvent e) {
        String beforeCut = beforeCutTextField.getText();// 获得截取前字符串
        String afterCut = afterCutTextField.getText();// 获得截取后字符串
        String beforeReplace = beforeReplaceTextField.getText();// 获得替换前字符串
        String afterReplace = afterReplaceTextField.getText();// 获得替换后字符串
        String fileType = fileTypeTextField.getText();// 获得文件类型
        if (selectFiles == null) {
            JOptionPane.showMessageDialog(this, "请选择文件所在文件夹!", "警告信息", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (selectFiles.length == 0) {
            JOptionPane.showMessageDialog(this, "选中文件夹为空文件夹!", "警告信息", JOptionPane.WARNING_MESSAGE);
            return;
        }
        textArea.setText("");// 清空文本域中数据
        for (File selectFile : selectFiles) {
            String fileName = selectFile.getName();// 获得文件名
            if (!beforeCut.isEmpty()) {
                int beforeCutIndex = fileName.indexOf(beforeCut);// 获得截取前字符串索引位置
                fileName = fileName.substring(beforeCutIndex + beforeCut.length());// 截取字符串
            }
            if (!afterCut.isEmpty()) {
                int afterCutIndex = fileName.lastIndexOf(afterCut);// 获得截取后字符串索引位置
                fileName = fileName.substring(0, afterCutIndex);// 截取字符串
                if (fileType.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "请输入文件类型!", "警告信息", JOptionPane.WARNING_MESSAGE);
                    return;
                } else {
                    if (fileType.contains(".")) {// 判断用户输入的文件类型是否包括“.”
                        fileName = fileName.concat(fileName);// 增加文件类型
                    } else {
                        fileName = fileName.concat("." + fileType);// 增加文件类型
                    }
                }
            } else if (!fileType.isEmpty()) {
                int fileTypeindex = fileName.lastIndexOf(".");// 获得文件类型索引位置
                fileName = fileName.substring(0, fileTypeindex);// 截取文件类型
                if (fileType.contains(".")) {// 判断用户输入的文件类型是否包括“.”
                    fileName = fileName.concat(fileName);// 增加文件类型
                } else {
                    fileName = fileName.concat("." + fileType);// 增加文件类型
                }
            }
            if (!(beforeReplace.isEmpty() && afterReplace.isEmpty())) {
                fileName = fileName.replace(beforeReplace, afterReplace);// 替换字符串
            }

            fileName = selectFile.getParent() + File.separator + fileName;// 获得修改后的文件名
            if (choiceCheckBox.isSelected()) {
                textArea.append(fileName + "\n\r");// 在文本区中显示重命名的结果
                selectFile.renameTo(new File(fileName));// 重命名文件
            } else {
                textArea.append(fileName + "\n\r");// 重命名文件

            }
        }
    }
}

  
 
  • 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
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253

如图

重命名前:

如图

重命名后:

如图

如图

二、题目描述-批量移动文件

1、题目

题目:实现一个批量移动文件的工具

2、解题思路

创建一个类:FileMoveTool

使用FileMoveTool继承JFrame构建窗体

文件批量移动的方法是使用File类中的renameTo()方法,renameTo()方法除了可以修改文件名,还能修改文件的绝对路径,达到文件移动目的。

3、代码详解

package com.xiaoxuzhu;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
/**
 * Description: 批量移动文件
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/3.1	    xiaoxuzhu		2022/5/3		    Create
 * </pre>
 * @date 2022/5/3
 */
public class FileMoveTool extends JFrame {

    /**
     *
     */
    private JPanel contentPane;
    private JTextField sourceTextField;
    private JTextField targetTextField;
    private File[] selectFiles;
    private File targetDirectory;
    private JTable table;

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

    /**
     * Create the frame.
     */
    public FileMoveTool() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);
        panel.setLayout(new GridLayout(2, 1, 5, 5));

        JPanel sourcePanel = new JPanel();
        panel.add(sourcePanel);

        JLabel sourceLabel = new JLabel("选择源文件:");
        sourcePanel.add(sourceLabel);

        sourceTextField = new JTextField();
        sourcePanel.add(sourceTextField);
        sourceTextField.setColumns(17);

        JButton sourceButton = new JButton("选择文件");
        sourceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_sourceButton_actionPerformed(e);
            }
        });
        sourcePanel.add(sourceButton);

        JPanel targetPanel = new JPanel();
        panel.add(targetPanel);

        JLabel targetLabel = new JLabel("选择目标文件夹:");
        targetPanel.add(targetLabel);

        targetTextField = new JTextField();
        targetPanel.add(targetTextField);
        targetTextField.setColumns(14);

        JButton targetButton = new JButton("选择文件夹");
        targetButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_targetButton_actionPerformed(e);
            }
        });
        targetPanel.add(targetButton);

        JPanel buttonPanel = new JPanel();
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        JButton moveButton = new JButton("移动");
        moveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_moveButton_actionPerformed(e);
            }
        });
        buttonPanel.add(moveButton);

        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_closeButton_actionPerformed(e);
            }
        });
        buttonPanel.add(closeButton);

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

        table = new JTable();
        DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得表格模型
        model.setColumnIdentifiers(new String[] { "移动文件名称", "目标文件夹" });
        table.setModel(model);
        scrollPane.setViewportView(table);
    }

    protected void do_sourceButton_actionPerformed(ActionEvent e) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得表格模型
        if (model.getRowCount() != 0) {
            model.setRowCount(0);
        }
        table.setModel(model);
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(true);
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            selectFiles = chooser.getSelectedFiles();
            if (selectFiles.length != 0) {
                StringBuilder fileNames = new StringBuilder();
                for (File selectFile : selectFiles) {
                    fileNames.append(selectFile.getName() + "、");
                }
                fileNames.deleteCharAt(fileNames.length() - 1);
                sourceTextField.setText(fileNames.toString());
            }
        }
    }

    protected void do_targetButton_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            targetDirectory = chooser.getSelectedFile();
            targetTextField.setText(targetDirectory.getAbsolutePath());
        }
    }

    protected void do_moveButton_actionPerformed(ActionEvent e) {
        if ((selectFiles == null) || (selectFiles.length == 0)) {
            JOptionPane.showMessageDialog(this, "请选择需要移动的文件!", "警告信息", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (targetDirectory == null) {
            JOptionPane.showMessageDialog(this, "请选择目标文件夹!", "警告信息", JOptionPane.WARNING_MESSAGE);
            return;
        }
        DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得表格模型
        for (File selectFile : selectFiles) {
            String fileName = targetDirectory.getAbsolutePath() + File.separator + selectFile.getName();// 获得新文件名
            selectFile.renameTo(new File(fileName));// 移动文件
            model.addRow(new String[] { selectFile.getName(), targetDirectory.getAbsolutePath() });// 向表格模型中增加数据
        }
        table.setModel(model);// 设置表格模型
    }

    protected void do_closeButton_actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}


  
 
  • 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
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197

如图

移动前:

如图

移动后:

如图

4、多学一个知识点

移动1G的文件,从D盘某个目录到C盘某个目录下,时间花费:10s左右。

使用renameTo()方法,可以毫秒级内移动成功。

注意事项:

1、如果被重命名的文件已存在,那么renameTo()不会成功

2、renameTo()方法在window系统下,进行移动是正常的。

3、renameTo()方法在linux系统下,进行移动会有问题

原因:renameTo方法移动失败是文件系统不一样形成的

解决方案:可以使用hutool的FileUtil.move(java.io.File, java.io.File, boolean)

		//1、目录移到目录
		File srcFile = FileUtil.file("C:\\Users\\Administrator\\Desktop\\xuzhu\\moveTest");
		//目标目录不存在程序也会帮忙创建
		File destFile = FileUtil.file("C:\\Users\\Administrator\\Desktop\\xuzhu\\targetMoveTest");

		FileUtil.move(srcFile, destFile, true);


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如图

三、题目描述-批量删除tmp文件

1、题目

题目:系统运行一段时间后,会产生大量的tmp文件,会影响系统性能。

实现:做一个批量删除指定文件夹里的tmp文件工具

2、解题思路

创建一个类:TempDeletionTool

使用TempDeletionTool继承JFrame构建窗体

遍历指定目录下的文件,查找指定类型的文件,过滤的方法是用File类的listFiles方法进行过滤

使用File类中的delete()方法删除指定的文件

3、代码详解

package com.xiaoxuzhu;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
/**
 * Description: 批量删除文件
 *
 * @author xiaoxuzhu
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本	        修改人		修改日期			修改内容
 * 2022/5/3.1	    xiaoxuzhu		2022/5/3		    Create
 * </pre>
 * @date 2022/5/3
 */

public class TempDeletionTool extends JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 891173527384201765L;
    private JPanel contentPane;
    private JTable table;
    private JTextField textField;
    private File[] tempFiles;

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

    /**
     * Create the frame.
     */
    public TempDeletionTool() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);

        JLabel discChooseLabel = new JLabel("选择文件夹:");
        panel.add(discChooseLabel);

        JButton findButton = new JButton("选择文件夹");
        findButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_findButton_actionPerformed(e);
            }
        });

        textField = new JTextField();
        panel.add(textField);
        textField.setColumns(10);
        panel.add(findButton);

        JButton clearButton = new JButton("清理");
        clearButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_clearButton_actionPerformed(e);
            }
        });
        panel.add(clearButton);

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

        table = new JTable();
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setColumnIdentifiers(new String[] { "文件名称", "文件大小", "修改时间", "文件状态" });
        scrollPane.setViewportView(table);
    }

    protected void do_findButton_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        int result = chooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File directory = chooser.getSelectedFile();
            textField.setText(directory.getAbsolutePath());
            tempFiles = directory.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    String fileName = pathname.getName();
                    if (fileName.endsWith("tmp") || fileName.endsWith("TMP")) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (File tempFile : tempFiles) {
                model.addRow(new Object[] { tempFile.getName(), tempFile.length(), format.format(new Date(tempFile.lastModified())), "未处理" });
            }
            table.setModel(model);
        }
    }

    protected void do_clearButton_actionPerformed(ActionEvent e) {
        if ((tempFiles == null) || (tempFiles.length == 0)) {// 判断用户选择的文件夹是否包括temp文件
            JOptionPane.showMessageDialog(this, "选择的文件夹中未包含tmp文件!", "警告信息", JOptionPane.WARNING_MESSAGE);
            return;
        }
        DefaultTableModel model = (DefaultTableModel) table.getModel();// 获得表格模型
        for (int i = 0; i < tempFiles.length; i++) {
            if (tempFiles[i].delete()) { // 删除文件
                model.setValueAt("已处理", i, 3);// 修改表格内容
            }
        }
    }
}



  
 
  • 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
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153

如图

如图

四、推荐专栏

《JAVA从零到壹》

《JAVA从零到壹》第八讲:系统常用类

《Hutool实战》7hutool实战:FileUtil 文件工具类(100多个文件常用操作方法)

五、示例源码下载

关注下面的公众号,回复筑基+题目号

筑基54

文章来源: xiaoxuzhu.blog.csdn.net,作者:小虚竹,版权归原作者所有,如需转载,请联系作者。

原文链接:xiaoxuzhu.blog.csdn.net/article/details/124720181

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200