Java fast batch move file implementation method

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

File moving is a common operation of computer resource management, which can be achieved by cutting and copying files or dragging the mouse in the operating system. But most of the programmatic implementation of Java files is done by copying the files to the destination and then deleting all the files. This is not a problem for small files, but moving several large files can slow things down and waste system resources. This example USES the renameTo() method of the File class to move files quickly without waiting too long to move even a few gigabytes.

Thought analysis:

The first is the view layer. Here's a suggestion, because in some control's events, other controls are often accessed, and the control's event methods take almost the same parameters as the fixed ActionEvent class, passing few other parameters. So even if the view is automatically generated by dragging controls, set those controls as member variables of the class in your code. In this example, use JPanel controls as the container of other controls, JLabel control used to display information, fixed JTextField control used to display to move files and target folder, JButton control used to select the source folder, target folder, and realize mobile and close the program, the JScrollPane, used to display the bar column and JTextArea control used to display the operation record.
Then there is the model layer. For the browse button, to get the array of File names in the source folder and the path to the target folder, you need to define a fil-type array member variable to hold the File name and a fil-type member variable to hold the target path.
After selecting the browse button of the source file, first create a JFileChooser file selector, using the setMultiSelectionEnabled(true) of the JFileChooser class. Method Settings can be selected multiple times, through the JFileChooser class showOpenDialog(this); Method to display the File selection dialog box, if the user confirms, use the getSelectedFiles() method of JFileChooser class to get the selected array of files and assign the value to the previously defined File type array member variable, clear the text box by the setText("") method of JTextField() class to remove the record of the last operation, create a new StringBuilder object, loop through the File array using foreach(), The append() method of the StringBuilder class is used to concatenate the file name, because there is an ", "in front of it. The substring () method of the StringBuilder class is used to get the string of all the file names, and the setText () method of the JTextFieldl class is used to display the file name string to the text box.
For the browse button of selecting the target folder, first create a JFileChooser file selector, use the setFileSelectionMode () method of JFileChooser class to set the selector to only work for the folder, show the file open dialog box through the showOpenDialog () method of JFileChooser class, and use the getSelectedFile() method of JFileChooser class to get the selected folder. Finally, display the folder to the text box using the setText () method of the JTextField control.
For mobile button event processing method, the first to use an array of array length attribute judgment files of any element, if use the foreach () loop through the files array, the array of each element to create a moving target File, through JTextArea controls append () method shows mobile records, using the File class renameTo () method implementation File move, finally USES the JTextArea control append () method shows mobile complete information.
For the event handling method of the close button, exit the program using the exit() method of the System class.
The code is as follows:


import java.awt.EventQueue;

public class QuickMoveFiles extends JFrame {

    
    private static final long serialVersionUID = -666045931923008374L;
    private JPanel contentPane;
    private JTextArea infoArea;
    private JTextField sourceFolderField;
    private JTextField targetFolderField;
    private File[] files;
    private File dir;

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

    
    public QuickMoveFiles() {
        setTitle("u5FEBu901Fu6279u91CFu79FBu52A8u6587u4EF6");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 507, 299);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        GridBagLayout gbl_contentPane = new GridBagLayout();
        gbl_contentPane.columnWidths = new int[] { 0, 178, 0, 0, 0, 0 };
        gbl_contentPane.rowHeights = new int[] { 0, 0, 169, 0, 0 };
        gbl_contentPane.columnWeights = new double[] { 0.0, 1.0, 0.0, 0.0, 0.0,
                Double.MIN_VALUE };
        gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 1.0, 0.0,
                Double.MIN_VALUE };
        contentPane.setLayout(gbl_contentPane);

        JLabel label = new JLabel("u9009u62E9u6E90u6587u4EF6uFF1A");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.anchor = GridBagConstraints.EAST;
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 0;
        gbc_label.gridy = 0;
        contentPane.add(label, gbc_label);

        sourceFolderField = new JTextField();
        GridBagConstraints gbc_sourceFolderField = new GridBagConstraints();
        gbc_sourceFolderField.gridwidth = 3;
        gbc_sourceFolderField.insets = new Insets(0, 0, 5, 5);
        gbc_sourceFolderField.fill = GridBagConstraints.HORIZONTAL;
        gbc_sourceFolderField.gridx = 1;
        gbc_sourceFolderField.gridy = 0;
        contentPane.add(sourceFolderField, gbc_sourceFolderField);
        sourceFolderField.setColumns(10);

        JButton browserButton1 = new JButton("u6D4Fu89C8");
        browserButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_browserButton1_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_browserButton1 = new GridBagConstraints();
        gbc_browserButton1.insets = new Insets(0, 0, 5, 0);
        gbc_browserButton1.gridx = 4;
        gbc_browserButton1.gridy = 0;
        contentPane.add(browserButton1, gbc_browserButton1);

        JLabel label_1 = new JLabel(
                "u9009u62E9u76EEu6807u6587u4EF6u5939uFF1A");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.EAST;
        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);

        targetFolderField = new JTextField();
        GridBagConstraints gbc_targetFolderField = new GridBagConstraints();
        gbc_targetFolderField.gridwidth = 3;
        gbc_targetFolderField.insets = new Insets(0, 0, 5, 5);
        gbc_targetFolderField.fill = GridBagConstraints.HORIZONTAL;
        gbc_targetFolderField.gridx = 1;
        gbc_targetFolderField.gridy = 1;
        contentPane.add(targetFolderField, gbc_targetFolderField);
        targetFolderField.setColumns(10);

        JButton browserButton2 = new JButton("u6D4Fu89C8");
        browserButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_browserButton2_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_browserButton2 = new GridBagConstraints();
        gbc_browserButton2.insets = new Insets(0, 0, 5, 0);
        gbc_browserButton2.gridx = 4;
        gbc_browserButton2.gridy = 1;
        contentPane.add(browserButton2, gbc_browserButton2);

        JLabel label_2 = new JLabel("u64CDu4F5Cu8BB0u5F55uFF1A");
        GridBagConstraints gbc_label_2 = new GridBagConstraints();
        gbc_label_2.anchor = GridBagConstraints.EAST;
        gbc_label_2.insets = new Insets(0, 0, 5, 5);
        gbc_label_2.gridx = 0;
        gbc_label_2.gridy = 2;
        contentPane.add(label_2, gbc_label_2);

        JScrollPane scrollPane = new JScrollPane();
        GridBagConstraints gbc_scrollPane = new GridBagConstraints();
        gbc_scrollPane.gridwidth = 4;
        gbc_scrollPane.insets = new Insets(0, 0, 5, 0);
        gbc_scrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = 1;
        gbc_scrollPane.gridy = 2;
        contentPane.add(scrollPane, gbc_scrollPane);

        infoArea = new JTextArea();
        scrollPane.setViewportView(infoArea);

        JButton moveButton = new JButton("u79FBu52A8");
        moveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_moveButton_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_moveButton = new GridBagConstraints();
        gbc_moveButton.insets = new Insets(0, 0, 0, 5);
        gbc_moveButton.gridx = 1;
        gbc_moveButton.gridy = 3;
        contentPane.add(moveButton, gbc_moveButton);

        JButton closeButton = new JButton("u5173u95ED");
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_closeButton_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_closeButton = new GridBagConstraints();
        gbc_closeButton.insets = new Insets(0, 0, 0, 5);
        gbc_closeButton.gridx = 2;
        gbc_closeButton.gridy = 3;
        contentPane.add(closeButton, gbc_closeButton);
    }

    
    protected void do_browserButton1_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();//Create a file selector
        chooser.setMultiSelectionEnabled(true);//Set the file to multiple options
        int option = chooser.showOpenDialog(this);//Displays the file open dialog box
        if (option == JFileChooser.APPROVE_OPTION) {
            files = chooser.getSelectedFiles();//Gets the selected array of files
            sourceFolderField.setText("");//Empty textbox
            StringBuilder filesStr = new StringBuilder();
            for (File file : files) {//Traverses the array of files
                filesStr.append(" , " + file.getName());//Connection file name
            }
            String str = filesStr.substring(1);//Gets a string for all file names
            sourceFolderField.setText(str);//Set the file name information to the text box
        } else {
            files = new File[0];
            sourceFolderField.setText("");//Empty textbox
        }
    }

    
    protected void do_browserButton2_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();//Create a file selector
        //The Settings selector only works for folders
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option = chooser.showOpenDialog(this);//Displays the file open dialog box
        if (option == JFileChooser.APPROVE_OPTION) {
            dir = chooser.getSelectedFile();//Gets the selected folder
            targetFolderField.setText(dir.toString());//Displays folder to text box
        } else {
            dir = null;
            targetFolderField.setText("");
        }
    }

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

    
    protected void do_moveButton_actionPerformed(ActionEvent e) {
        if (files.length <= 0 || dir == null)//Determines whether the file array has elements or not
            return;
        for (File file : files) {//Traverses the array of files
            File newFile = new File(dir, file.getName());//Create a moving target file
            infoArea.append(file.getName() + "t Move to the t" + dir);//Display movement record
            file.renameTo(newFile);//Move files
            infoArea.append("------ complete n");//Displays movement completion information
        }
        //Display operation completed
        infoArea.append("################## Operation is completed ###################n");
    }
}

The effect is as follows:
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201403/201431151435962.png" >


Related articles: