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、解題思路

創建一個類: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);
    }
}

移動前:

移動後:

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);

三、題目描述-批量刪除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);// 修改表格內容
            }
        }
    }
}

以上就是Java實現文件批量重命名,移動和刪除的詳細內容,更多關於Java文件重命名 移動 刪除的資料請關註WalkonNet其它相關文章!

推薦閱讀: