3

How do I write over a specific line in a text file using FileWriter and PrintWriter? I don't want to have to make a new file every time.

Edit: Can I just cycle through the file, get the length of the String at the indicated line number, and then use that length to backspace once I get to that line (to delete the String), and write in the new data?

public static void setVariable(int lineNumber, String data) {
    try { 
        // Creates FileWriter. Append is on.
        FileWriter fw = new FileWriter("data.txt", true);       

        PrintWriter pw = new PrintWriter(fw);       

        //cycles through file until line designated to be rewritten is reached
        for (int i = 1; i <= lineNumber; i++) {     
            //TODO: need to figure out how to change the append to false to overwrite data
            if (i == lineNumber) {
                pw.println(data);
                pw.close();
            } else {          
                // moves printwriter focus to next line (doesn't overwrite)
                pw.println(""); 
            }
        } 
    }
}
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Telle Miller
  • 43
  • 1
  • 1
  • 6

1 Answers1

11

If you are using Java 7 or higher and if lineNumber starts in 1, you can do the following:

public static void setVariable(int lineNumber, String data) throws IOException {
    Path path = Paths.get("data.txt");
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    lines.set(lineNumber - 1, data);
    Files.write(path, lines, StandardCharsets.UTF_8);
}

Obviously if lineNumber starts in 0, then:

lines.set(lineNumber, data);
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
  • Would this work with any line? E.g. I have 90 lines in the file and I want to write over the 34th. – Telle Miller Jul 13 '15 at 06:00
  • Do I import java.awt.List or java.util.List ? – Telle Miller Jul 13 '15 at 06:03
  • 2
    Ah! The *imports* are `import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List;`. :) – Paul Vargas Jul 13 '15 at 06:04
  • This causes two errors. The first is "The method readAllLines(Path, Charset) in the type Files is not applicable for the arguments (Path)" and the second is "The method write(Path, byte[], OpenOption...) in the type Files is not applicable for the arguments (Path, List)" – Telle Miller Jul 13 '15 at 06:05
  • Ah! Sorry! The code is for Java 8. *Updated* to Java 7. Try again. :) – Paul Vargas Jul 13 '15 at 06:09