加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java在文件中某个位置前后插入文本内容

(2013-05-02 11:08:52)
我们可以通过输入输出流向文件中追加内容.本文记录使用java修改,向指定位置前后添加内容的方法.
To edit file in java we need to search text which replace with new text. indexOf() method will search text in java and append() method will modify old content in string.
修改前文本文件中的内容

hello abc, goodbye xyz

完整代码:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaIOEditFileExample {

        public static void main(String[] args) {

                File f = new File("c:\\appendOldFile.txt");
                FileInputStream fs = null;
                InputStreamReader in = null;
                BufferedReader br = null;

                StringBuffer sb = new StringBuffer();

                String textinLine;

                try {
                        fs = new FileInputStream(f);
                        in = new InputStreamReader(fs);
                        br = new BufferedReader(in);

                        while (true) {
                                textinLine = br.readLine();
                                if (textinLine == null)
                                        break;
                                sb.append(textinLine);
                        }
                        String textToEdit1 = "abc";
                        int cnt1 = sb.indexOf(textToEdit1);
                        sb.replace(cnt1, cnt1 + textToEdit1.length(), "码农");

                        String textToEdit2 = "xyz";
                        int cnt2 = sb.indexOf(textToEdit2);
                        sb.replace(cnt2, cnt2 + textToEdit2.length(), textToEdit2
                                        + " and 哈利波特");

                        fs.close();
                        in.close();
                        br.close();

                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                try {
                        FileWriter fstream = new FileWriter(f);
                        BufferedWriter outobj = new BufferedWriter(fstream);
                        outobj.write(sb.toString());
                        outobj.close();

                        System.out.println("Done");
                } catch (Exception e) {
                        System.err.println("Error: " + e.getMessage());
                }
        }
}


修改后文件中的内容
hello 码农, goodbye xyz and 哈利波特

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有