zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java实现文件批量重命名具体实例

JAVA实例 实现 重命名 具体 文件批量
2023-06-13 09:15:18 时间

Windows操作系统可以实现重命名文件操作,却不能实现批量重命名。本实例实现了批量重命名功能,可以将一个文件夹内同一类型的文件按照一定的规则批量重命名。用户可以给出重命名模板,程序可以根据模板对相应的文件进行重命名。此外,还可以在重命名模板中添加特殊符号,程序会将这些特殊符号替换成重命名后的文件编号。

思路分析:

1.先看视图层,需要一些JLabel控件分别显示指示用户的信息,三个JTextField控件分别显示所选路径、输入文件名模板即输入扩展名,两个JButton控件分别用来浏览文件夹和开始重命名,一个JSeparator控件表示分割线,一个JSpinner控件代表开始编号,一个JScrollPane控件作为容器,在里面放置一个JTable控件列出旧文件名和新文件名。
2.再看模型层。首先定义浏览按钮的事件处理方法,在该方法中创建一个JFileChooser文件选择器,使用JFileChooser类的setFileSelectionMode()方法设置只选择文件夹,通过JFileChooser类的showOpenDialog()显示打开对话框,若用户点击确认按钮则使用JFileChooser类的getSelectedFile()方法获取选中的文件夹,最后使用JTextField控件的setText()方法显示文件夹信息。
3.定义一个类来实现FileFilter接口,在该类的构造方法中保存文件扩展名,然后定义一个方法,在该方法中使用String类的endsWith()方法来过滤文件扩展名。
4.然后定义开始按钮的事件处理方法,首先使用JTextField控件的getText()方法获取模板字符串,若为空则通过JOptionPane类的showMessageDialog()方法提示用户输入模板,然后创建DefaultTableModel对象并使用JTable类的getModel()方法获取表格数据模型,用JTable类的setRowCount(0);方法清除表格数据,使用JSpinner类的getValue()方法获取起始编号,使用String类的indexOf方法获取第一个“#”的索引,使用String类的substring()方法获取模板中数字占位字符串,使用String类的replace()方法把模板中数字占位字符串替换为指定格式,为了规范使用String类的toLowerCase()方法将用户输入的扩展名转换为小写形式,若用户未输入“.”则补上,然后使用File类的listFiles()方法获取文件夹中的文件列表数组,使用foreach()循环遍历每个文件,通过String类的format()方法格式化每个文件名称,使用DefaultTableModel类的addRow()方法把文件的旧名称和新名称添加到表格的数据模型中,使用File类的getParentFile()方法获取目标文件所在的文件夹对象,创建一个File对象并初始化为新的文件名,最后使用File类的renameTo()方法实现文件重命名。
代码如下:

复制代码代码如下:


importjava.awt.EventQueue;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.io.File;
importjava.io.FileFilter;

importjavax.swing.JButton;
importjavax.swing.JFileChooser;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JPanel;
importjavax.swing.JScrollPane;
importjavax.swing.JSeparator;
importjavax.swing.JSpinner;
importjavax.swing.JTable;
importjavax.swing.JTextField;
importjavax.swing.border.EmptyBorder;
importjavax.swing.table.DefaultTableModel;
importjava.awt.GridBagLayout;
importjava.awt.GridBagConstraints;
importjava.awt.Insets;

/**
 *获取文件列表的过滤器
 * 
 *@author李钟尉
 */
publicclassRenameFilesextendsJFrame{

   /**
    * 
    */
   privatestaticfinallongserialVersionUID=4534371106024773867L;

   privatefinalclassExtNameFileFilterimplementsFileFilter{
       privateStringextName;

       publicExtNameFileFilter(StringextName){
           this.extName=extName;//保存文件扩展名
       }

       @Override
       publicbooleanaccept(Filepathname){
           //过滤文件扩展名
           if(pathname.getName().toUpperCase()
                   .endsWith(extName.toUpperCase()))
               returntrue;
           returnfalse;
       }
   }

   privateJPanelcontentPane;
   privateJTextFieldforderField;
   privateJTextFieldtempletField;
   privateFiledir;
   privateJTabletable;
   privateJTextFieldextNameField;
   privateJSpinnerstartSpinner;

   /**
    *Launchtheapplication.
    */
   publicstaticvoidmain(String[]args){
       EventQueue.invokeLater(newRunnable(){
           publicvoidrun(){
               try{
                   RenameFilesframe=newRenameFiles();
                   frame.setVisible(true);
               }catch(Exceptione){
                   e.printStackTrace();
               }
           }
       });
   }

   /**
    *Createtheframe.
    */
   publicRenameFiles(){
       setResizable(false);
       setTitle("文件批量重命名");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setBounds(100,100,383,409);
       contentPane=newJPanel();
       contentPane.setBorder(newEmptyBorder(5,5,5,5));
       setContentPane(contentPane);
       GridBagLayoutgbl_contentPane=newGridBagLayout();
       gbl_contentPane.columnWidths=newint[]{72,54,60,87,91,0};
       gbl_contentPane.rowHeights=newint[]{25,25,10,25,24,25,2,
               216,0};
       gbl_contentPane.columnWeights=newdouble[]{0.0,0.0,0.0,0.0,0.0,
               Double.MIN_VALUE};
       gbl_contentPane.rowWeights=newdouble[]{0.0,0.0,0.0,0.0,0.0,
               0.0,0.0,0.0,Double.MIN_VALUE};
       contentPane.setLayout(gbl_contentPane);

       JLabellabel=newJLabel();
       label.setText("文件批量重命名模块:");
       GridBagConstraintsgbc_label=newGridBagConstraints();
       gbc_label.fill=GridBagConstraints.VERTICAL;
       gbc_label.insets=newInsets(0,0,5,5);
       gbc_label.gridwidth=3;
       gbc_label.gridx=1;
       gbc_label.gridy=0;
       contentPane.add(label,gbc_label);

       JLabellabel_1=newJLabel();
       label_1.setText("文件路径:");
       GridBagConstraintsgbc_label_1=newGridBagConstraints();
       gbc_label_1.anchor=GridBagConstraints.EAST;
       gbc_label_1.fill=GridBagConstraints.VERTICAL;
       gbc_label_1.insets=newInsets(0,0,5,5);
       gbc_label_1.gridx=0;
       gbc_label_1.gridy=1;
       contentPane.add(label_1,gbc_label_1);

       forderField=newJTextField();
       forderField.setText("");
       GridBagConstraintsgbc_forderField=newGridBagConstraints();
       gbc_forderField.fill=GridBagConstraints.HORIZONTAL;
       gbc_forderField.insets=newInsets(0,0,5,5);
       gbc_forderField.gridwidth=3;
       gbc_forderField.gridx=1;
       gbc_forderField.gridy=1;
       contentPane.add(forderField,gbc_forderField);

       JButtonbutton=newJButton();
       button.addActionListener(newActionListener(){
           publicvoidactionPerformed(ActionEvente){
               do_button_actionPerformed(e);
           }
       });
       button.setText("浏览");
       GridBagConstraintsgbc_button=newGridBagConstraints();
       gbc_button.anchor=GridBagConstraints.NORTHWEST;
       gbc_button.insets=newInsets(0,0,5,0);
       gbc_button.gridx=4;
       gbc_button.gridy=1;
       contentPane.add(button,gbc_button);

       JSeparatorseparator_1=newJSeparator();
       GridBagConstraintsgbc_separator_1=newGridBagConstraints();
       gbc_separator_1.fill=GridBagConstraints.BOTH;
       gbc_separator_1.insets=newInsets(0,0,5,0);
       gbc_separator_1.gridwidth=5;
       gbc_separator_1.gridx=0;
       gbc_separator_1.gridy=2;
       contentPane.add(separator_1,gbc_separator_1);

       JLabellabel_5=newJLabel();
       label_5.setText("使用#可以指定数字计数所占的位置,使用*可以插入原文件名:");
       GridBagConstraintsgbc_label_5=newGridBagConstraints();
       gbc_label_5.fill=GridBagConstraints.VERTICAL;
       gbc_label_5.insets=newInsets(0,0,5,0);
       gbc_label_5.gridwidth=5;
       gbc_label_5.gridx=0;
       gbc_label_5.gridy=3;
       contentPane.add(label_5,gbc_label_5);

       JLabellabel_3=newJLabel();
       label_3.setText(" 模板:");
       GridBagConstraintsgbc_label_3=newGridBagConstraints();
       gbc_label_3.anchor=GridBagConstraints.EAST;
       gbc_label_3.fill=GridBagConstraints.VERTICAL;
       gbc_label_3.insets=newInsets(0,0,5,5);
       gbc_label_3.gridx=0;
       gbc_label_3.gridy=4;
       contentPane.add(label_3,gbc_label_3);

       templetField=newJTextField();
       templetField.setText("catrestaurant###");
       GridBagConstraintsgbc_templetField=newGridBagConstraints();
       gbc_templetField.anchor=GridBagConstraints.SOUTH;
       gbc_templetField.fill=GridBagConstraints.HORIZONTAL;
       gbc_templetField.insets=newInsets(0,0,5,5);
       gbc_templetField.gridwidth=3;
       gbc_templetField.gridx=1;
       gbc_templetField.gridy=4;
       contentPane.add(templetField,gbc_templetField);

       JLabellabel_4=newJLabel();
       label_4.setText("开始于:");
       GridBagConstraintsgbc_label_4=newGridBagConstraints();
       gbc_label_4.fill=GridBagConstraints.VERTICAL;
       gbc_label_4.insets=newInsets(0,0,5,5);
       gbc_label_4.gridx=0;
       gbc_label_4.gridy=5;
       contentPane.add(label_4,gbc_label_4);

       startSpinner=newJSpinner();
       GridBagConstraintsgbc_startSpinner=newGridBagConstraints();
       gbc_startSpinner.fill=GridBagConstraints.HORIZONTAL;
       gbc_startSpinner.insets=newInsets(0,0,5,5);
       gbc_startSpinner.gridx=1;
       gbc_startSpinner.gridy=5;
       contentPane.add(startSpinner,gbc_startSpinner);

       JLabellabel_2=newJLabel();
       label_2.setText(" 扩展名:");
       GridBagConstraintsgbc_label_2=newGridBagConstraints();
       gbc_label_2.fill=GridBagConstraints.HORIZONTAL;
       gbc_label_2.insets=newInsets(0,0,5,5);
       gbc_label_2.gridx=2;
       gbc_label_2.gridy=5;
       contentPane.add(label_2,gbc_label_2);

       JButtonstartButton=newJButton();
       startButton.addActionListener(newActionListener(){
           publicvoidactionPerformed(ActionEvente){
               do_startButton_actionPerformed(e);
           }
       });

       extNameField=newJTextField();
       extNameField.setText("jpg");
       GridBagConstraintsgbc_extNameField=newGridBagConstraints();
       gbc_extNameField.fill=GridBagConstraints.HORIZONTAL;
       gbc_extNameField.insets=newInsets(0,0,5,5);
       gbc_extNameField.gridx=3;
       gbc_extNameField.gridy=5;
       contentPane.add(extNameField,gbc_extNameField);
       startButton.setText("开始");
       GridBagConstraintsgbc_startButton=newGridBagConstraints();
       gbc_startButton.anchor=GridBagConstraints.NORTH;
       gbc_startButton.insets=newInsets(0,0,5,0);
       gbc_startButton.gridx=4;
       gbc_startButton.gridy=5;
       contentPane.add(startButton,gbc_startButton);

       JSeparatorseparator_2=newJSeparator();
       GridBagConstraintsgbc_separator_2=newGridBagConstraints();
       gbc_separator_2.anchor=GridBagConstraints.NORTH;
       gbc_separator_2.fill=GridBagConstraints.HORIZONTAL;
       gbc_separator_2.insets=newInsets(0,0,5,0);
       gbc_separator_2.gridwidth=5;
       gbc_separator_2.gridx=0;
       gbc_separator_2.gridy=6;
       contentPane.add(separator_2,gbc_separator_2);

       JScrollPanescrollPane=newJScrollPane();
       GridBagConstraintsgbc_scrollPane=newGridBagConstraints();
       gbc_scrollPane.fill=GridBagConstraints.BOTH;
       gbc_scrollPane.gridwidth=5;
       gbc_scrollPane.gridx=0;
       gbc_scrollPane.gridy=7;
       contentPane.add(scrollPane,gbc_scrollPane);

       table=newJTable();
       table.setModel(newDefaultTableModel(newObject[][]{},newString[]{
               "旧文件名","新文件名"}));
       scrollPane.setViewportView(table);
   }

   /**
    *浏览按钮的事件处理方法
    * 
    *@parame
    */
   protectedvoiddo_button_actionPerformed(ActionEvente){
       JFileChooserchooser=newJFileChooser();//创建文件选择器
       //设置只选择文件夹
       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
       intoption=chooser.showOpenDialog(this);//显示打开对话框
       if(option==JFileChooser.APPROVE_OPTION){
           dir=chooser.getSelectedFile();//获取选择的文件夹
       }else{
           dir=null;
       }
       forderField.setText(dir+"");//显示文件夹信息
   }

   /**
    *开始按钮的事件处理方法
    * 
    *@parame
    */
   protectedvoiddo_startButton_actionPerformed(ActionEvente){
       Stringtemplet=templetField.getText();//获取模板字符串
       if(templet.isEmpty()){
           JOptionPane.showMessageDialog(this,"请确定重命名模板","信息对话框",
                   JOptionPane.WARNING_MESSAGE);
           return;
       }
       //获取表格数据模型
       DefaultTableModelmodel=(DefaultTableModel)table.getModel();
       model.setRowCount(0);//清除表格数据
       intbi=(Integer)startSpinner.getValue();//获取起始编号
       intindex=templet.indexOf("#");//获取第一个“#”的索引
       Stringcode=templet.substring(index);//获取模板中数字占位字符串
       //把模板中数字占位字符串替换为指定格式
       templet=templet.replace(code,"%0"+code.length()+"d");
       StringextName=extNameField.getText().toLowerCase();
       if(extName.indexOf(".")==-1)
           extName="."+extName;
       //获取文件中文件列表数组
       File[]files=dir.listFiles(newExtNameFileFilter(extName));
       for(Filefile:files){//变量文件数组
           //格式化每个文件名称
           Stringname=String.format(templet,bi++)+extName;
           //把文件的旧名称与新名称添加到表格的数据模型
           model.addRow(newString[]{file.getName(),name});
           FileparentFile=file.getParentFile();//获取文件所在文件夹对象
           FilenewFile=newFile(parentFile,name);
           file.renameTo(newFile);//文件重命名
       }
   }
}

效果如图: