Java将传入参数的值作为变量写入文件中

查看:136
本文介绍了Java将传入参数的值作为变量写入文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

想要用Java实现一个功能:

public void foo(String ttl){
//将这个String类型的ttl值写入一个文件中
//但是文件是有内容的,如下:
//------------------------------------------------------------------------
//log.config:
//foo
//
//this is a log of my work and the ttl is : (此处写入传入参数ttl)。
//
//bar
//------------------------------------------------------------------------
    foo
    bar
 }

大概意思就是文件里写一个变量,把ttl这个传入参数的值传进文件的变量里,有办法实现么?
还望高手赐教。

解决方案

提供一个思路就是先读取文件内容,然后替换文件内容,再更新文件,文件太大的时候不太适合
代码:

package indi.andy.platform.web.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test {
    public static String read(File src) {
        StringBuffer res = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(src));
            while ((line = reader.readLine()) != null) {
                res.append(line + "\n");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res.toString();
    }

    public static boolean write(String cont, File dist) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(dist));
            writer.write(cont);
            writer.flush();
            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        File src = new File("D:/test.txt");
        // 读取
        String cont = read(src);
        // 更新
        cont = cont.replace("#ttl#", "写入的内容");
        write(cont, src);
    }
}

文件内容

//------------------------------------------------------------------------
//log.config:
//foo
//
//this is a log of my work and the ttl is : #ttl#
//
//bar
//------------------------------------------------------------------------

这篇关于Java将传入参数的值作为变量写入文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆