java替换文件中某一行文本的内容

时间:2025-03-19 09:19:53

个人博客 地址:/article/20180913160442

代码如下

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

/**
* @author 作者:范文皓
* @createDate 创建时间:2018年9月13日 下午3:59:07
*/
public class PropertyKit {
	public static  void main(String[] args) {
		String path=("/blog_config.txt").getPath() ;
		path=(1, ());
		replace(path,"theme","newTheme");
		String theme=("blog_config.txt").get("theme");
		(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 = ()) != null) {
	            	
	            	boolean isMath=(temp).split("=")[0].equals(key);
	            	
	                if(isMath){
	                    buf = (key+"="+newValue);
	                }else{
	                    buf = (temp);
	                }
	                buf = ((""));
	            }

	            ();
	            FileOutputStream fos = new FileOutputStream(file);
	            PrintWriter pw = new PrintWriter(fos);
	            (().toCharArray());
	            ();
	            ();
	        } catch (IOException e) {
	            ();
	        }
	    }
}

实现思路

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

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

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

相关文章