欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现查找文本内容替换功能示例

程序员文章站 2024-02-25 17:31:33
思路: 先看视图层,要有一个jbutton控件用来选择文件,一个jtextfield控件显示选中文件的绝对路径,一个jlabel控件提示用户输入搜索文本,一个jlabel...

思路:

先看视图层,要有一个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();
        }
    }
}


java实现查找文本内容替换功能示例