Java implementation file batch renaming concrete instances

  • 2020-04-01 03:02:49
  • OfStack

Windows operating system can achieve renaming file operation, but can not achieve batch renaming. This example realizes the batch rename function, which can rename the same type of files in a folder according to certain rules. The user can give the rename template, the program can rename the corresponding file according to the template. In addition, you can add special symbols to the renamed template, which the program replaces with the renamed file number.

Thought analysis:

1. Look at the view layer, need some JLabel controls respectively show that indicates the user's information, three JTextField controls respectively according to the selected path, the input file name extension template that is input, two JButton control to browse folders and began to rename a JSeparator control line, a representative a JSpinner controls began to number, a JScrollPane control as a container, placed inside a series control lists the old file name and the new file name.
2. Look at the model layer. Firstly, the event handling method of browse button is defined. In this method, a JFileChooser file selector is created. SetFileSelectionMode () method of JFileChooser class is set to only select the folder. Finally, you display the folder information using the setText () method of the JTextField control.
3. Define a class to implement the FileFilter interface, save the file extension in the constructor of the class, and then define a method to filter the file extension using the endsWith () method of the String class.
4. Then define the event handling method of the start button. First, the getText() method of the JTextField control is used to get the template string. If it is empty, the user is prompted to enter the template through the showMessageDialog () method of the JOptionPane class. Clear form data, the use of a JSpinner class getValue () method to obtain the starting number, use the String class indexOf method to get the first "#" index, use the substring of String class () method to obtain digital placeholder String in the template, use the String class replace () method of the template in the digital placeholder String substitution for the specified format, in order to standardize the use of the String class toLowerCase () method converts the extension of the user input lowercase, If users are not input ". "the patch, and then using the File class listFiles () method to get the folder list the files in the array, using the foreach () loop through each File, through the format of the String class format () method in each File name, using DefaultTableModel class addRow () method of the document of the old and new names added to the form of data model, using the File class getParentFile () method to obtain the target File in folder object, Create a File object, initialize it as the new File name, and finally rename the File using the renameTo () method of the File class.
The code is as follows:


import java.awt.EventQueue; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.File; 
import java.io.FileFilter; 

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.JSeparator; 
import javax.swing.JSpinner; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.border.EmptyBorder; 
import javax.swing.table.DefaultTableModel; 
import java.awt.GridBagLayout; 
import java.awt.GridBagConstraints; 
import java.awt.Insets; 


public class RenameFiles extends JFrame { 

    
    private static final long serialVersionUID = 4534371106024773867L; 

    private final class ExtNameFileFilter implements FileFilter { 
        private String extName; 

        public ExtNameFileFilter(String extName) { 
            this.extName = extName;//Save the file extension
        } 

        @Override
        public boolean accept(File pathname) { 
            //Filter file extensions
            if (pathname.getName().toUpperCase() 
                    .endsWith(extName.toUpperCase())) 
                return true; 
            return false; 
        } 
    } 

    private JPanel contentPane; 
    private JTextField forderField; 
    private JTextField templetField; 
    private File dir; 
    private JTable table; 
    private JTextField extNameField; 
    private JSpinner startSpinner; 

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

    
    public RenameFiles() { 
        setResizable(false); 
        setTitle(" Batch file renaming "); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setBounds(100, 100, 383, 409); 
        contentPane = new JPanel(); 
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
        setContentPane(contentPane); 
        GridBagLayout gbl_contentPane = new GridBagLayout(); 
        gbl_contentPane.columnWidths = new int[] { 72, 54, 60, 87, 91, 0 }; 
        gbl_contentPane.rowHeights = new int[] { 25, 25, 10, 25, 24, 25, 2, 
                216, 0 }; 
        gbl_contentPane.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 
                Double.MIN_VALUE }; 
        gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 
                0.0, 0.0, 0.0, Double.MIN_VALUE }; 
        contentPane.setLayout(gbl_contentPane); 

        JLabel label = new JLabel(); 
        label.setText(" File batch rename module: "); 
        GridBagConstraints gbc_label = new GridBagConstraints(); 
        gbc_label.fill = GridBagConstraints.VERTICAL; 
        gbc_label.insets = new Insets(0, 0, 5, 5); 
        gbc_label.gridwidth = 3; 
        gbc_label.gridx = 1; 
        gbc_label.gridy = 0; 
        contentPane.add(label, gbc_label); 

        JLabel label_1 = new JLabel(); 
        label_1.setText(" File path: "); 
        GridBagConstraints gbc_label_1 = new GridBagConstraints(); 
        gbc_label_1.anchor = GridBagConstraints.EAST; 
        gbc_label_1.fill = GridBagConstraints.VERTICAL; 
        gbc_label_1.insets = new Insets(0, 0, 5, 5); 
        gbc_label_1.gridx = 0; 
        gbc_label_1.gridy = 1; 
        contentPane.add(label_1, gbc_label_1); 

        forderField = new JTextField(); 
        forderField.setText(""); 
        GridBagConstraints gbc_forderField = new GridBagConstraints(); 
        gbc_forderField.fill = GridBagConstraints.HORIZONTAL; 
        gbc_forderField.insets = new Insets(0, 0, 5, 5); 
        gbc_forderField.gridwidth = 3; 
        gbc_forderField.gridx = 1; 
        gbc_forderField.gridy = 1; 
        contentPane.add(forderField, gbc_forderField); 

        JButton button = new JButton(); 
        button.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                do_button_actionPerformed(e); 
            } 
        }); 
        button.setText(" browse "); 
        GridBagConstraints gbc_button = new GridBagConstraints(); 
        gbc_button.anchor = GridBagConstraints.NORTHWEST; 
        gbc_button.insets = new Insets(0, 0, 5, 0); 
        gbc_button.gridx = 4; 
        gbc_button.gridy = 1; 
        contentPane.add(button, gbc_button); 

        JSeparator separator_1 = new JSeparator(); 
        GridBagConstraints gbc_separator_1 = new GridBagConstraints(); 
        gbc_separator_1.fill = GridBagConstraints.BOTH; 
        gbc_separator_1.insets = new Insets(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); 

        JLabel label_5 = new JLabel(); 
        label_5.setText(" use # You can specify the position occupied by the number count, using * You can insert the original file name: "); 
        GridBagConstraints gbc_label_5 = new GridBagConstraints(); 
        gbc_label_5.fill = GridBagConstraints.VERTICAL; 
        gbc_label_5.insets = new Insets(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); 

        JLabel label_3 = new JLabel(); 
        label_3.setText("   Template: "); 
        GridBagConstraints gbc_label_3 = new GridBagConstraints(); 
        gbc_label_3.anchor = GridBagConstraints.EAST; 
        gbc_label_3.fill = GridBagConstraints.VERTICAL; 
        gbc_label_3.insets = new Insets(0, 0, 5, 5); 
        gbc_label_3.gridx = 0; 
        gbc_label_3.gridy = 4; 
        contentPane.add(label_3, gbc_label_3); 

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

        JLabel label_4 = new JLabel(); 
        label_4.setText(" Started in: "); 
        GridBagConstraints gbc_label_4 = new GridBagConstraints(); 
        gbc_label_4.fill = GridBagConstraints.VERTICAL; 
        gbc_label_4.insets = new Insets(0, 0, 5, 5); 
        gbc_label_4.gridx = 0; 
        gbc_label_4.gridy = 5; 
        contentPane.add(label_4, gbc_label_4); 

        startSpinner = new JSpinner(); 
        GridBagConstraints gbc_startSpinner = new GridBagConstraints(); 
        gbc_startSpinner.fill = GridBagConstraints.HORIZONTAL; 
        gbc_startSpinner.insets = new Insets(0, 0, 5, 5); 
        gbc_startSpinner.gridx = 1; 
        gbc_startSpinner.gridy = 5; 
        contentPane.add(startSpinner, gbc_startSpinner); 

        JLabel label_2 = new JLabel(); 
        label_2.setText("   Extension: "); 
        GridBagConstraints gbc_label_2 = new GridBagConstraints(); 
        gbc_label_2.fill = GridBagConstraints.HORIZONTAL; 
        gbc_label_2.insets = new Insets(0, 0, 5, 5); 
        gbc_label_2.gridx = 2; 
        gbc_label_2.gridy = 5; 
        contentPane.add(label_2, gbc_label_2); 

        JButton startButton = new JButton(); 
        startButton.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                do_startButton_actionPerformed(e); 
            } 
        }); 

        extNameField = new JTextField(); 
        extNameField.setText("jpg"); 
        GridBagConstraints gbc_extNameField = new GridBagConstraints(); 
        gbc_extNameField.fill = GridBagConstraints.HORIZONTAL; 
        gbc_extNameField.insets = new Insets(0, 0, 5, 5); 
        gbc_extNameField.gridx = 3; 
        gbc_extNameField.gridy = 5; 
        contentPane.add(extNameField, gbc_extNameField); 
        startButton.setText(" start "); 
        GridBagConstraints gbc_startButton = new GridBagConstraints(); 
        gbc_startButton.anchor = GridBagConstraints.NORTH; 
        gbc_startButton.insets = new Insets(0, 0, 5, 0); 
        gbc_startButton.gridx = 4; 
        gbc_startButton.gridy = 5; 
        contentPane.add(startButton, gbc_startButton); 

        JSeparator separator_2 = new JSeparator(); 
        GridBagConstraints gbc_separator_2 = new GridBagConstraints(); 
        gbc_separator_2.anchor = GridBagConstraints.NORTH; 
        gbc_separator_2.fill = GridBagConstraints.HORIZONTAL; 
        gbc_separator_2.insets = new Insets(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); 

        JScrollPane scrollPane = new JScrollPane(); 
        GridBagConstraints gbc_scrollPane = new GridBagConstraints(); 
        gbc_scrollPane.fill = GridBagConstraints.BOTH; 
        gbc_scrollPane.gridwidth = 5; 
        gbc_scrollPane.gridx = 0; 
        gbc_scrollPane.gridy = 7; 
        contentPane.add(scrollPane, gbc_scrollPane); 

        table = new JTable(); 
        table.setModel(new DefaultTableModel(new Object[][] {}, new String[] { 
                " The old name of the file ", " The new file name " })); 
        scrollPane.setViewportView(table); 
    } 

    
    protected void do_button_actionPerformed(ActionEvent e) { 
        JFileChooser chooser = new JFileChooser();//Create a file selector
        //Set to select only folders
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
        int option = chooser.showOpenDialog(this);//Displays the open dialog box
        if (option == JFileChooser.APPROVE_OPTION) { 
            dir = chooser.getSelectedFile();//Gets the selected folder
        } else { 
            dir = null; 
        } 
        forderField.setText(dir + "");//Display folder information
    } 

    
    protected void do_startButton_actionPerformed(ActionEvent e) { 
        String templet = templetField.getText();//Get template string
        if (templet.isEmpty()) { 
            JOptionPane.showMessageDialog(this, " Be sure to rename the template ", " Information dialog box ", 
                    JOptionPane.WARNING_MESSAGE); 
            return; 
        } 
        //Get the tabular data model
        DefaultTableModel model = (DefaultTableModel) table.getModel(); 
        model.setRowCount(0);//Clear table data
        int bi = (Integer) startSpinner.getValue();//Get start number
        int index = templet.indexOf("#");//Gets the index of the first "#"
        String code = templet.substring(index);//Gets a numeric placeholder string in the template
        //Replaces the numeric placeholder string in the template with the specified format
        templet = templet.replace(code, "%0" + code.length() + "d"); 
        String extName = extNameField.getText().toLowerCase(); 
        if (extName.indexOf(".") == -1) 
            extName = "." + extName; 
        //Gets an array of the list of files in the file
        File[] files = dir.listFiles(new ExtNameFileFilter(extName)); 
        for (File file : files) {//Variable file array
            //Format each file name
            String name = String.format(templet, bi++) + extName; 
            //Add the old name of the file with the new name to the data model of the table
            model.addRow(new String[] { file.getName(), name }); 
            File parentFile = file.getParentFile();//Gets the folder object where the file resides
            File newFile = new File(parentFile, name); 
            file.renameTo(newFile);//File renaming
        } 
    } 
} 

The effect is as follows:

< img border = 0 SRC = "/ / img.jbzj.com/file_images/article/201402/2014228164301413.png" >


Related articles: