Java文件重命名 移动 删除
小虚竹and掘金 人气:0一、题目描述-批量重命名
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);// 修改表格内容 } } } }
加载全部内容