java實現尋找常值內容替換功能樣本_java

來源:互聯網
上載者:User

思路:

先看視圖層,要有一個JButton控制項用來選擇檔案,一個JTextField控制項顯示選中檔案的絕對路徑,一個JLabel控制項提示使用者輸入搜尋文本,一個JLabel控制項提示使用者輸入替換後的文本,一個JTextField標籤供使用者輸入要搜尋的文本,一個JTextField標籤供使用者輸入替換後的文本,一個JButton控制項執行替換,一個JButton控制項用來開啟修改後的檔案。
對於選擇檔案按鈕,使用JButton類的addActionListener()方法為其綁定事件,在該事件中定義actionPerformed()函數,在該函數體中調用選擇檔案的方法。
在選擇檔案方法中,首先建立JFileChooser檔案選取器,使用JFileChooser類的setFileFilter()方法建立副檔名過濾器,再使用JFileChooser類的setFileSelectionMode()方法設定檔案選擇模式為檔案,通過JFileChooser類的showOpenDialog()方法顯示檔案開啟對話方塊,確定使用者按下開啟按鈕,而非取消按鈕後,通過JFileChooser類的getSelectedFile()方法擷取使用者選擇的檔案對象,使用JTextField類的setText()方法顯示檔案資訊到文字框。
對於替換按鈕,同選擇檔案按鈕,使用JButton類的addActionListener()方法為其綁定事件,在該事件中定義actionPerformed()函數,在該函數體中調用替換文本的方法。
在替換文本方法中,首先使用TextField類的getText()方法擷取要搜尋的文本和要替換成的文本,若搜尋文本不為空白則嘗試建立FileReader檔案輸入資料流和char緩衝字元數組以及StringBuilder字串構建器,在while()迴圈中使用FileReader類的read()方法讀取檔案內容到字串構建器,讀取完畢後使用FileReader類的close()方法關閉輸入資料流,使用StringBuilder類的replace()方法從構建器中產生字串,並替換搜尋文本,然後建立FileWriter檔案輸出資料流,使用FileWriter類的write()方法把替換完成的字串寫入檔案內,然後使用FileWriter類的close()方法關閉輸出資料流,然後依次捕獲FileNotFoundException異常和IOException異常,最後使用JOptionPane類的showMessageDialog()方法提示使用者替換完成。
對於開啟檔案按鈕,使用JButton類的addActionListener()方法為其綁定事件,在該事件中定義actionPerformed()函數,在該函數體中調用開啟檔案的方法。
在開啟檔案方法中嘗試使用 Desktop.getDesktop().edit(file);,並捕獲IOException異常。
代碼如下:

複製代碼 代碼如下:

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;

    /**
     * Launch the application.
     */
    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();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    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("選擇檔案");
        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("搜尋文本:");
        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("替換為:");
        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("替換");
        replaceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_replaceButton_actionPerformed(e);
            }
        });
        panel_1.add(replaceButton);

        JButton openfileButton = new JButton("開啟檔案");
        openfileButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                do_button_2_actionPerformed(e);
            }
        });
        panel_1.add(openfileButton);
    }

    /**
     * 選擇檔案按鈕事件處理方法
     *
     * @param e
     */
    protected void do_button_actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser("./");// 建立檔案選取器
        // 設定副檔名過濾器
        chooser.setFileFilter(new FileNameExtensionFilter("文字檔", "txt",
                "java", "php", "html", "htm"));
        // 設定檔案選擇模式
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        // 顯示檔案開啟對話方塊
        int option = chooser.showOpenDialog(this);
        // 確定使用者按下開啟按鈕,而非取消按鈕
        if (option != JFileChooser.APPROVE_OPTION)
            return;
        // 擷取使用者選擇的檔案對象
        file = chooser.getSelectedFile();
        // 顯示檔案資訊到文字框
        fileField.setText(file.toString());
    }

    /**
     * 替換按鈕的事件處理方法
     *
     * @param e
     */
    protected void do_replaceButton_actionPerformed(ActionEvent event) {
        String searchText = searchTextField.getText();// 擷取搜尋文本
        String replaceText = replaceTextField.getText();// 擷取替換文本
        if (searchText.isEmpty())
            return;
        try {
            FileReader fis = new FileReader(file);// 建立檔案輸入資料流
            char[] data = new char[1024];// 建立緩衝字元數組
            int rn = 0;
            StringBuilder sb = new StringBuilder();// 建立字串構建器
            while ((rn = fis.read(data)) > 0) {// 讀取檔案內容到字串構建器
                String str = String.valueOf(data, 0, rn);
                sb.append(str);
            }
            fis.close();// 關閉輸入資料流
            // 從構建器中產生字串,並替換搜尋文本
            String str = sb.toString().replace(searchText, replaceText);
            FileWriter fout = new FileWriter(file);// 建立檔案輸出資料流
            fout.write(str.toCharArray());// 把替換完成的字串寫入檔案內
            fout.close();// 關閉輸出資料流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JOptionPane.showMessageDialog(null, "替換完成");
    }

    /**
     * 開啟檔案按鈕的事件處理方法。
     *
     * @param e
     */
    protected void do_button_2_actionPerformed(ActionEvent e) {
        try {
            if (file == null)
                return;
            Desktop.getDesktop().edit(file);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.