-1

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.

henny888
  • 1
  • 1
  • 4
  • i would suggest you read up more on File Handling. It is pretty routine to do so, and you wouldnt want a readymade answer but try out stuff yourself – Hrishikesh Jan 15 '14 at 13:41
  • To get help here, you should show what you have tried. – Magnilex Jan 15 '14 at 13:42
  • 1
    If the replacement content is exactly the same number of _bytes_ as the original then you could replace it using a RandomAccessFile, otherwise all you can really do is read the file line by line and write the modified text to a new file. – Ian Roberts Jan 15 '14 at 13:42
  • you can't change a single line as it changes the size of the file. you need to overwrite the whole file. – njzk2 Jan 15 '14 at 13:43
  • @Magnilex I've tried basically most if not all topics related to this matter and have even tried myself. – henny888 Jan 15 '14 at 13:50
  • @njzk2 So basically I'd have to overwrite the whole file? – henny888 Jan 15 '14 at 13:51
  • at least everything down from your point of modification. – njzk2 Jan 15 '14 at 13:51

1 Answers1

4

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.

beny1700
  • 284
  • 1
  • 4
  • 10