Java implementation find text content substitution features sample _java

Source: Internet
Author: User
Tags gettext

Ideas:

First look at the view layer, there is a JButton control to select the file, a JTextField control display the absolute path of the selected file, a JLabel control prompts the user to enter the search text, a JLabel control prompts the user to enter the replacement text, A JTextField label for the user to enter the text to search for, a JTextField label for the user to enter the replaced text, a JButton control to perform the substitution, and a JButton control to open the modified file.
For the Select File button, use the addActionListener () method of the JButton class to bind the event, define the actionperformed () function in the event, and invoke the method of selecting the file in the function body.
In the Select File method, first create the JFileChooser file selector and use the Setfilefilter () method of the JFileChooser class to create the file name extension filter. Then use the Setfileselectionmode () method of the JFileChooser class to set the file selection mode as a file, through the JFileChooser class's Showopendialog () method to display the File Open dialog box, to determine that the user presses the Open button, Instead of the Cancel button, the Getselectedfile () method of the JFileChooser class gets the file object selected by the user, using the JTextField class's SetText () method to display the file information to the text box.
For the replacement button, the same selection file button uses the addActionListener () method of the JButton class to bind the event, in which the actionperformed () function is defined, and the method of replacing text is called in the function body.
In the alternate text method, first use the GetText () method of the TextField class to get the text to search for and the text to replace. If the search text is not empty, try to create the FileReader file input stream and char buffer character array and the StringBuilder string Builder to read the file contents to the string builder in the while () loop using the FileReader class's Read () method. After reading, use the Close () method of the FileReader class to turn off the input stream, use the Replace () method of the StringBuilder class to generate a string from the builder, replace the search text, and then create the FileWriter file output stream. Use the Write () method of the FileWriter class to write the replacement string to the file, and then use the close () method of the FileWriter class to turn off the output stream. The filenotfoundexception exception and the IOException exception are then captured sequentially, and the Showmessagedialog () method of the Joptionpane class is used to prompt the user to replace the completion.
For the Open File button, use the addActionListener () method of the JButton class to bind the event, define the actionperformed () function in the event, and call the method that opens the file in the function body.
In the open file method, try to use Desktop.getdesktop (). Edit (file), and catch the IOException exception.
The code is as follows:

Copy Code code 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;

/**
* 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 ("Select 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 file");
Openfilebutton.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Do_button_2_actionperformed (e);
}
});
Panel_1.add (Openfilebutton);
}

/**
* Select File button Event handling method
*
* @param E
*/
protected void do_button_actionperformed (ActionEvent e) {
JFileChooser chooser = new JFileChooser ("./");//Create File Selector
Set file name extension filter
Chooser.setfilefilter (New Filenameextensionfilter ("Text file", "TXT",
"Java", "PHP", "html", "htm");
Set File selection mode
Chooser.setfileselectionmode (jfilechooser.files_only);
Show File Open dialog box
int option = Chooser.showopendialog (this);
Determines that the user presses the Open button, not the Cancel button
if (option!= jfilechooser.approve_option)
Return
Gets the file object selected by the user
File = Chooser.getselectedfile ();
Display file information to a text box
Filefield.settext (File.tostring ());
}

/**
* Event-handling method for the Replace button
*
* @param E
*/
protected void Do_replacebutton_actionperformed (ActionEvent event) {
String SearchText = Searchtextfield.gettext ();//Get search text
String replacetext = Replacetextfield.gettext ();//Get alternate text
if (Searchtext.isempty ())
Return
try {
FileReader fis = new FileReader (file);
char[] data = new char[1024];//Create buffer character array
int rn = 0;
StringBuilder sb = new StringBuilder ();//Create String Builder
while (rn = Fis.read (data)) > 0 {//Read 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
To generate a string from the builder and replace the search text
String str = sb.tostring (). replace (SearchText, replacetext);
FileWriter fout = new FileWriter (file);//create Files output stream
Fout.write (Str.tochararray ());//write the replacement string into the file
Fout.close ()//close output stream
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
Joptionpane.showmessagedialog (NULL, "replace complete");
}

/**
* Open the event handling method for the file button.
*
* @param E
*/
protected void do_button_2_actionperformed (ActionEvent e) {
try {
if (file = = null)
Return
Desktop.getdesktop (). edit (file);
catch (IOException E1) {
E1.printstacktrace ();
}
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.