Modify existing line in file - Java [duplicate]

空扰寡人 提交于 2019-12-13 23:31:14

问题


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

File contents:

Heinrich: 30
George: 2020
Fred: 9090129

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

EDIT: Or would it be better off just using YAML?

Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/21138971/modify-existing-line-in-file-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!