首页 > 其他 > 详细

Java查找替换文本文件内容

时间:2014-02-28 08:29:18      阅读:557      评论:0      收藏:0      [点我收藏+]

文本替换几乎是所有文本编辑器都支持的功能,但是要限制在编辑其中才可以执行该功能。本实例实现了制定文本文件的内容替换,并且不需要再编辑其中打开文本文件。

思路:

  1. 先看视图层,要有一个JButton控件用来选择文件,一个JTextField控件显示选中文件的绝对路径,一个JLabel控件提示用户输入搜索文本,一个JLabel控件提示用户输入替换后的文本,一个JTextField标签供用户输入要搜索的文本,一个JTextField标签供用户输入替换后的文本,一个JButton控件执行替换,一个JButton控件用来打开修改后的文件。
  2. 对于选择文件按钮,使用JButton类的addActionListener()方法为其绑定事件,在该事件中定义actionPerformed()函数,在该函数体中调用选择文件的方法。
  3. 在选择文件方法中,首先创建JFileChooser文件选择器,使用JFileChooser类的setFileFilter()方法创建文件扩展名过滤器,再使用JFileChooser类的setFileSelectionMode()方法设置文件选择模式为文件,通过JFileChooser类的showOpenDialog()方法显示文件打开对话框,确定用户按下打开按钮,而非取消按钮后,通过JFileChooser类的getSelectedFile()方法获取用户选择的文件对象,使用JTextField类的setText()方法显示文件信息到文本框。
  4. 对于替换按钮,同选择文件按钮,使用JButton类的addActionListener()方法为其绑定事件,在该事件中定义actionPerformed()函数,在该函数体中调用替换文本的方法。
  5. 在替换文本方法中,首先使用TextField类的getText()方法获取要搜索的文本和要替换成的文本,若搜索文本不为空则尝试创建FileReader文件输入流和char缓冲字符数组以及StringBuilder字符串构建器,在while()循环中使用FileReader类的read()方法读取文件内容到字符串构建器,读取完毕后使用FileReader类的close()方法关闭输入流,使用StringBuilder类的replace()方法从构建器中生成字符串,并替换搜索文本,然后创建FileWriter文件输出流,使用FileWriter类的write()方法把替换完成的字符串写入文件内,然后使用FileWriter类的close()方法关闭输出流,然后依次捕获FileNotFoundException异常和IOException异常,最后使用JOptionPane类的showMessageDialog()方法提示用户替换完成。
  6. 对于打开文件按钮,使用JButton类的addActionListener()方法为其绑定事件,在该事件中定义actionPerformed()函数,在该函数体中调用打开文件的方法。
  7. 在打开文件方法中尝试使用 Desktop.getDesktop().edit(file);,并捕获IOException异常。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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();
        }
    }
}

  效果如图:

bubuko.com,布布扣

Java查找替换文本文件内容,布布扣,bubuko.com

Java查找替换文本文件内容

原文:http://www.cnblogs.com/cysolo/p/3571419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!