java修改txt文本中的内容

需求:将文本放在服务器下,并修改文本中的值,

1,获取服务器地址

public Configuration getStandardConfig() {
        //获取服务器的webapp路径  
        ServletContext context = ServletActionContext.getServletContext();

        File file = new File(context.getRealPath("/"));
        String path = file.getParentFile().getParentFile().getParentFile().getAbsolutePath();
        Configuration standardConfig = new Configuration(path+"\\listSvr.ini");

        return standardConfig;
    }

2.将值写入文本中

public static void replaceTxtByStr(String oldStr,Integer replaceStr) { 
      String temp = "";
      Properties prop = new Properties();
      try { 
          //获取服务器的webapp路径  
            ServletContext context = ServletActionContext.getServletContext();
            File file1 = new File(context.getRealPath("/"));
            String path = file1.getParentFile().getParentFile().getParentFile().getAbsolutePath();
            File file = new File(path+"\\listSvr.ini");

            FileInputStream fis = new FileInputStream(file); 
            InputStreamReader isr = new InputStreamReader(fis); 
            BufferedReader br = new BufferedReader(isr); 
            StringBuffer buf = new StringBuffer(); 
            // 保存该行前面的内容  

             // 保存该行前面的内容  

            for (int j = 1; (temp = br.readLine()) != null 
                    && !(temp.replaceAll(" ", "").split("=")[0].toString()).equals(oldStr); j++) { 
                buf = buf.append(temp); 
                buf = buf.append(System.getProperty("line.separator")); 
            } 
 /**当所写行的=前面的内容与oldStr相同时,修改本行中的内容
             *修改后的值为temp1
             */
            String temp1 = temp.replaceAll(temp.replaceAll(" ", "").split("=")[1].toString(), "" +replaceStr);
            buf = buf.append(temp1); 

            // 保存该行后面的内容 
            while ((temp = br.readLine()) != null) { 
                buf = buf.append(System.getProperty("line.separator")); 
                buf = buf.append(temp); 
            } 

            br.close(); 
            FileOutputStream fos = new FileOutputStream(file); 
            PrintWriter pw = new PrintWriter(fos); 
            pw.write(buf.toString().toCharArray()); 
            pw.flush(); 
            pw.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
      } 
  • 7
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值