How to replace a specific line in a file using Java?

我怕爱的太早我们不能终老 提交于 2019-12-22 13:07:24

问题


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(""); 
            }
        } 
    }
}

回答1:


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);


来源:https://stackoverflow.com/questions/31375972/how-to-replace-a-specific-line-in-a-file-using-java

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