zoukankan      html  css  js  c++  java
  • java替换文件中某一行文本的内容


    个人博客 地址:http://www.wenhaofan.com/article/20180913160442

    代码如下

    package com.wenhaofan.common.kit;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    
    import com.jfinal.kit.PropKit;
    
    /**
    * @author 作者:范文皓
    * @createDate 创建时间:2018年9月13日 下午3:59:07
    */
    public class PropertyKit {
    	public static  void main(String[] args) {
    		String path=FileKit.class.getResource("/blog_config.txt").getPath() ;
    		path=path.substring(1, path.length());
    		replace(path,"theme","newTheme");
    		String theme=PropKit.use("blog_config.txt").get("theme");
    		System.out.println(theme);
    	 
    		
    	}
    	public static void replace(String path,String key,String newValue) {
    	       String temp = "";
    	        try {
    	            File file = new File(path);
    	            FileInputStream fis = new FileInputStream(file);
    	            InputStreamReader isr = new InputStreamReader(fis);
    	            BufferedReader br = new BufferedReader(isr);
    	            StringBuffer buf = new StringBuffer();
    
    	            // 保存该行前面的内容
    	            while ( (temp = br.readLine()) != null) {
    	            	
    	            	boolean isMath=StrKit.filterNull(temp).split("=")[0].equals(key);
    	            	
    	                if(isMath){
    	                    buf = buf.append(key+"="+newValue);
    	                }else{
    	                    buf = buf.append(temp);
    	                }
    	                buf = buf.append(System.getProperty("line.separator"));
    	            }
    
    	            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();
    	        }
    	    }
    }

    实现思路

        按行读取指定文本中的内容,将内容添加进StringBuffer中,

        如果当前行号为指定行号则添加替换的内容,否则添加原内容

        然后将StringBuffer中的内容覆盖写入文件

  • 相关阅读:
    Linux常见命令
    CSS以及JQuery总是忽略掉的小问题
    HTML DOM appendChild() 方法
    WINUSB使用(附STM32Demo)
    STM32H7系列调试使用DCMI过程中若干注意事项
    godot初涉
    【转】使用objdump看内核源码
    scrcpy rk3399 交叉编译 meson
    gitlab hooks 钩子实现服务器代码同步至文件夹
    Linux编译笔记
  • 原文地址:https://www.cnblogs.com/fanwenhao/p/9641165.html
Copyright © 2011-2022 走看看