io 操作文件内容

来源:互联网 发布:淘宝350模板如何加链接 编辑:程序博客网 时间:2024/04/30 20:43
package com.thunisoft.np.fy.test;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;public class Test {    public static void main(String[] args) {        Test t = new Test();        t.readFileByLines("d://blxt.log");            }        public  void readFileByLines(String fileName){        FileInputStream fis = null ;        try {         fis = new FileInputStream(fileName); //创建文件输入流         InputStreamReader isr = new InputStreamReader(fis,"GB2312"); //指定读取流为GBK编码格式         BufferedReader br = new BufferedReader(isr); //创建字符缓存输入流         String str ="";         while((str=br.readLine()) != null){          System.out.println(str); //读取每行文本          String newStr = replace(str,"WARN","你妈");          appendMethodB("d://test2.txt", newStr+"\r\n");         }        } catch (FileNotFoundException e) {         e.printStackTrace();        } catch (UnsupportedEncodingException e) {         e.printStackTrace();        } catch (IOException e) {         e.printStackTrace();        }finally{         if(fis != null){          try {           fis.close();          } catch (IOException e) {           e.printStackTrace();          }         }        }        }        public static void appendMethodB(String fileName, String content){        try {        //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件       FileWriter writer = new FileWriter(fileName, true);        writer.write(content);        writer.close();        } catch (IOException e) {        e.printStackTrace();        }        }    private String replace(String orgstr,String fromStr,String toStr){        String result = orgstr.replaceFirst(fromStr, toStr);        return result;    }}


 

原创粉丝点击