替換文字檔案中指定的內容

sanqima發表於2014-06-11

      文字替換幾乎是所有文字編輯器都支援的功能,但是要限制在編輯器中才可以執行該功能。

本例項實現了指定文字檔案中的內容替換,並且不需要再編輯器中開啟文字檔案。例項的執行效果如下圖所示。

(1)替換前;         (2)替換後。

用到了兩個方法:

 (1)append()方法

  利用StringBuilder類的append()方法,可以向該類的物件尾部追加字串文字,該方法的宣告如下:

    public StringBuilder append(String str) 該方法支援過載

(2)replace()方法

  替換字串要通過String類的replace()方法實現,該方法的宣告如下:

    public String replace(CharSequence target, CharSequence replacement)

  引數宣告:

  target: 目標字串

  replace門頭:替換的新字串

 

完整程式碼如下:

package cn.whut.num;


import java.awt.Desktop;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class ReplaceFileText extends JFrame {

	
	private static final long serialVersionUID = 1L;
	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() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JButton button = new JButton("\u9009\u62E9\u6587\u4EF6");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				do_button_actionPerformed(e);
			}
			
		});
		button.setBounds(32, 23, 93, 23);
		contentPane.add(button);
		
		JLabel label = new JLabel("\u641C\u7D22\u6587\u672C\uFF1A");
		label.setHorizontalAlignment(SwingConstants.CENTER);
		label.setBounds(32, 56, 93, 15);
		contentPane.add(label);
		
		JLabel label_1 = new JLabel("\u66FF\u6362\u4E3A\uFF1A");
		label_1.setHorizontalAlignment(SwingConstants.CENTER);
		label_1.setBounds(32, 92, 93, 15);
		contentPane.add(label_1);
		
		fileField = new JTextField();
		fileField.setBounds(149, 24, 213, 21);
		contentPane.add(fileField);
		fileField.setColumns(10);
		
		searchTextField = new JTextField();
		searchTextField.setBounds(149, 53, 213, 21);
		contentPane.add(searchTextField);
		searchTextField.setColumns(10);
		
		replaceTextField = new JTextField();
		replaceTextField.setBounds(149, 89, 213, 21);
		contentPane.add(replaceTextField);
		replaceTextField.setColumns(10);
		
		JButton replaceButton = new JButton("\u66FF\u6362");
		replaceButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				do_replaceButton_actionPerformed(e);
			}
			
		});
		replaceButton.setBounds(110, 139, 93, 23);
		contentPane.add(replaceButton);
		
		JButton openfileButton = new JButton("\u6253\u5F00\u6587\u4EF6");
		openfileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				do_button_2_actionPerformed(e);
			}
		});
		openfileButton.setBounds(246, 139, 93, 23);
		contentPane.add(openfileButton);
	}
	
	private void do_button_actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser("./");
		//設定檔案的副檔名,以方便過濾
		chooser.setFileFilter(new FileNameExtensionFilter("文字檔案", "txt",
				         "java","php","html","htm"));
		//顯示檔案開啟的對話方塊
		int option = chooser.showOpenDialog(this);
		//確定使用者按下“開啟”按鈕,而非取消按鈕
		if(option != JFileChooser.APPROVE_OPTION)
			return;
		//獲取使用者選擇的檔案物件
		file = chooser.getSelectedFile();
		//顯示檔案資訊到文字框
		fileField.setText(file.toString());
		
	}
	
	private void do_replaceButton_actionPerformed(ActionEvent e) {
		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();//關閉輸入流
			//從構建器中生成字串,並替換searchText文字
			String str = sb.toString().replace(searchText, replaceText);
			FileWriter fout = new FileWriter(file);//建立檔案輸出流
			fout.write(str.toCharArray()); //把替換完成的字串寫入檔案
			fout.close();//關閉輸出流,很重要。
			
		}catch(FileNotFoundException e1){
			e1.printStackTrace();
		}catch(IOException e2){
			e2.printStackTrace();
		}
		JOptionPane.showMessageDialog(null, "替換完成");
		
	}	

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


 

 

 

相關文章