比如说我的记事本内容如下:
121304020001 1 13-4-2 08:29:21:47
121304020002 2 13-4-2
121304020003 3 13-4-2 08:30:40:46
121304020004 4 13-4-2 08:31:40:71
我现在只想修改每行开头的一串数字,其他不用管,比如说我要给第四行的一串数字加1000变成121304021004!!
怎么弄哦?

解决方案 »

  1.   

    用BufferedReader读,用PrintWriter写
      

  2.   


    package nec.reflex.demo;import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class ModifyString {

    public static void main(String[] args){
    Pattern pattern = Pattern.compile("^\\d+"); 
    String str = "";
    StringBuffer  bstr = new StringBuffer();
    try {
    BufferedReader br =new BufferedReader(new InputStreamReader(new FileInputStream("./demo.txt")));

    while((str=br.readLine())!= null){
    Matcher matcher = pattern.matcher(str);
    if (matcher.find(0))
    {
    BigDecimal  bl = new BigDecimal(matcher.group(0));
    bl = bl.add(new BigDecimal(1000));
    str = str.replace(matcher.group(0),""+bl.toString());
    }
    bstr.append(str+"\r\n");
    }


    FileWriter fw = new FileWriter(new File("./demo.txt"));
    fw.write("");
    fw.flush();
    fw.write(bstr.toString());
    fw.flush();
    br.close();
    fw.close();
    } catch (FileNotFoundException e) {
    System.out.println("文件未找到");
    } catch (IOException e) {
    System.out.println("IO异常");
    //e.printStackTrace();
    }
    }
    }测试通过