Java implementation of the find text content replacement function example

  • 2020-04-01 03:03:45
  • OfStack

Ideas:

Look at the view layer, want to have a JButton control used to select a file, a JTextField control according to the absolute path selected files, a JLabel control prompt the user for the search text, prompt the user for a JLabel controls replace text, after a JTextField tags to search for users to input text, a JTextField label for users to input text after the replacement, replacing a JButton control implementation, a JButton control used to open a modified file.
For the select file button, use the addActionListener () method of the JButton class to bind the event to it, define the actionPerformed () function in the event, and call the method to select the file in the body of the function.
In select files approach, first create JFileChooser file selector, use setFileFilter JFileChooser class () method to create file extensions filter, reuse of JFileChooser setFileSelectionMode () method to set the file selection mode to file, through JFileChooser class showOpenDialog () method to display file open dialog box, determine the user press the open button, rather than after the cancel button, Get the file object selected by the user through the getSelectedFile() method of the JFileChooser class, and display the file information to the text box using the setText() method of the JTextField class.
For the replace button, use the addActionListener () method of the JButton class to bind the event to the same file button, define the actionPerformed () function in the event, and call the method to replace the text in the body of the function.
In replacement text approach, the first to use the TextField class getText () method to search for text and to replace text, if the search text no empty, try to create FileReader file input stream and char buffer character array and StringBuilder string builder, in the while () loop FileReader class read () method is used to read the file content to the builder of the string, read after using FileReader class close () method to close the input stream, Use the replace () method of the StringBuilder class to generate the string from the builder and replace the search text, then create the FileWriter output stream, write the replaced string to the file using the write () method of the FileWriter class, then close the output stream using the close() method of the FileWriter class, and then catch the FileNotFoundException and IOException exception in turn, Finally, the showMessageDialog () method of the JOptionPane class prompts the user to complete the replacement.
For the open file button, use the addActionListener () method of the JButton class to bind the event to it, define the actionPerformed () function in the event, and call the open file method in the function body.
Try using desktop.getdesktop ().edit(file) in the open file method; , and catch IOException exceptions.
The code is as follows:


import java.awt.BorderLayout;

public class ReplaceFileText extends JFrame {

    
    private static final long serialVersionUID = 8674569541853793419L;
    private JPanel contentPane;
    private JTextField fileField;
    private JTextField searchTextField;
    private JTextField replaceTextField;
    private File file;

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

    
    public ReplaceFileText() {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 501, 184);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(10, 91));
        contentPane.add(panel, BorderLayout.CENTER);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[] { 81, 0, 0, 66, 0 };
        gbl_panel.rowHeights = new int[] { 23, 0, 0, 0, 0 };
        gbl_panel.columnWeights = new double[] { 0.0, 0.0, 0.0, 1.0,
                Double.MIN_VALUE };
        gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0,
                Double.MIN_VALUE };
        panel.setLayout(gbl_panel);

        JButton button = new JButton(" Select the file ");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_actionPerformed(e);
            }
        });
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.anchor = GridBagConstraints.NORTHWEST;
        gbc_button.insets = new Insets(0, 0, 5, 5);
        gbc_button.gridx = 0;
        gbc_button.gridy = 0;
        panel.add(button, gbc_button);

        fileField = new JTextField();
        fileField.setEditable(false);
        GridBagConstraints gbc_fileField = new GridBagConstraints();
        gbc_fileField.gridwidth = 3;
        gbc_fileField.insets = new Insets(0, 0, 5, 0);
        gbc_fileField.fill = GridBagConstraints.HORIZONTAL;
        gbc_fileField.gridx = 1;
        gbc_fileField.gridy = 0;
        panel.add(fileField, gbc_fileField);
        fileField.setColumns(10);

        JLabel label = new JLabel(" Search text: ");
        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 = 1;
        panel.add(label, gbc_label);

        searchTextField = new JTextField();
        GridBagConstraints gbc_searchTextField = new GridBagConstraints();
        gbc_searchTextField.gridwidth = 3;
        gbc_searchTextField.insets = new Insets(0, 0, 5, 0);
        gbc_searchTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_searchTextField.gridx = 1;
        gbc_searchTextField.gridy = 1;
        panel.add(searchTextField, gbc_searchTextField);
        searchTextField.setColumns(10);

        JLabel label_1 = new JLabel(" Replace with: ");
        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 = 2;
        panel.add(label_1, gbc_label_1);

        replaceTextField = new JTextField();
        GridBagConstraints gbc_replaceTextField = new GridBagConstraints();
        gbc_replaceTextField.gridwidth = 3;
        gbc_replaceTextField.insets = new Insets(0, 0, 5, 0);
        gbc_replaceTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_replaceTextField.gridx = 1;
        gbc_replaceTextField.gridy = 2;
        panel.add(replaceTextField, gbc_replaceTextField);
        replaceTextField.setColumns(10);

        JPanel panel_1 = new JPanel();
        GridBagConstraints gbc_panel_1 = new GridBagConstraints();
        gbc_panel_1.gridwidth = 4;
        gbc_panel_1.fill = GridBagConstraints.BOTH;
        gbc_panel_1.gridx = 0;
        gbc_panel_1.gridy = 3;
        panel.add(panel_1, gbc_panel_1);

        JButton replaceButton = new JButton(" replace ");
        replaceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_replaceButton_actionPerformed(e);
            }
        });
        panel_1.add(replaceButton);

        JButton openfileButton = new JButton(" Open the file ");
        openfileButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_2_actionPerformed(e);
            }
        });
        panel_1.add(openfileButton);
    }

    
    protected void do_button_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser("./");//Create a file selector
        //Set the file extension filter
        chooser.setFileFilter(new FileNameExtensionFilter(" Text file ", "txt",
                "java", "php", "html", "htm"));
        //Set the file selection mode
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        //Displays the file open dialog box
        int option = chooser.showOpenDialog(this);
        //Make sure the user presses the open button instead of the cancel button
        if (option != JFileChooser.APPROVE_OPTION)
            return;
        //Gets the file object selected by the user
        file = chooser.getSelectedFile();
        //Displays file information to the text box
        fileField.setText(file.toString());
    }

    
    protected void do_replaceButton_actionPerformed(ActionEvent event) {
        String searchText = searchTextField.getText();//Get search text
        String replaceText = replaceTextField.getText();//Get replacement text
        if (searchText.isEmpty())
            return;
        try {
            FileReader fis = new FileReader(file);//Create a file input stream
            char[] data = new char[1024];//Creates an array of buffered characters
            int rn = 0;
            StringBuilder sb = new StringBuilder();//Create a string builder
            while ((rn = fis.read(data)) > 0) {//Reads the contents of the file to the string builder
                String str = String.valueOf(data, 0, rn);
                sb.append(str);
            }
            fis.close();//Close the input stream
            //Generates a string from the builder and replaces the search text
            String str = sb.toString().replace(searchText, replaceText);
            FileWriter fout = new FileWriter(file);//Create a file output stream
            fout.write(str.toCharArray());//Writes the replaced string to a file
            fout.close();//Close the output stream
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JOptionPane.showMessageDialog(null, " Replace completed ");
    }

    
    protected void do_button_2_actionPerformed(ActionEvent e) {
        try {
            if (file == null)
                return;
            Desktop.getDesktop().edit(file);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201402/20140227152604.jpg? 2014127152627 ">


Related articles: