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.

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top