修改文件中的现有行-Java [英] Modify existing line in file - Java

查看:72
本文介绍了修改文件中的现有行-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助或代码示例来更新现有行.

I need some help or code examples to update an existing line.

文件内容:

Heinrich: 30
George: 2020
Fred: 9090129

说,如果我想将乔治的值更新(写)为300,我将如何实现呢?

Say if I wanted to update (write) George's value to say 300, how would I achieve this?

或者仅使用YAML会更好吗?

Or would it be better off just using YAML?

谢谢.

推荐答案

这里是一种方法,请尝试一下.在此示例中,文件为 C:/user.txt ,并且我将George的值更改为 1234

Here is a way to do it, try it. In this example the file is C:/user.txt and i change the value of George by 1234

public class George {
    private static List<String> lines;

    public static void main (String [] args) throws IOException{
        File f = new File("C:/user.txt");
        lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
        changeValueOf("Georges", 1234); // the name and the value you want to modify
        Files.write(f.toPath(), changeValueOf("George", 1234), Charset.defaultCharset());
    }

    private static List<String> changeValueOf(String username, int newVal){
        List<String> newLines = new ArrayList<String>();
        for(String line: lines){
            if(line.contains(username)){
                String [] vals = line.split(": ");
                newLines.add(vals[0]+": "+String.valueOf(newVal));
            }else{
                newLines.add(line);
            }

        }
        return newLines;
    }
}

这是一个可行的解决方案,但我认为还有其他一些更有效的方法.

This is a working solution, but i think there is some other way more efficient.

这篇关于修改文件中的现有行-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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