javafilefileupdate

How can i Update a File in Java, which class Should i use?


my program has the following code,

BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File("xyz.dat"),true));
                        bufWriter.write(nameField+"/"+ageField+"/"+genderField+"\n");
                        bufWriter.flush();

Which creates a file.. Sample Format of data stored in file..

Name1/Age1/Gender1                            // for user1
Name2/Age2/Gender2                            // for user2
.
.
.
NameN/AgeN/GenderN                            //for userN

Suppose I need to change the age of the user5 then how can i do it? I can navigate to the 5th user and I can get the data through the split("/",3);method but how to make changes for that particular user ? I am really very confused here.


Solution

  • 1) Solution for a short file (which fits in memory) with Java 7

    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    String line5 = replaceAge(lines.get(4), newAge);
    lines.set(4, line5);
    Path tmp = Files.createTempFile(prefix, suffix, attrs);
    Files.write(path, lines)
    Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    

    2) For a big file

        Path tmp = Files.createTempFile(prefix, suffix, attrs);
        try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
                BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            for (int i = 1; (line = br.readLine()) != null; i++) {
                if (i == 5) {
                    line = replaceAge(line, newAge);
                }
                bw.write(line);
                bw.newLine();
            }
        }
        Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);