如何使用FileWriter和PrintWriter在文本文件中的特定行上书写?我不想每次都制作一个新文件。

编辑:我可以循环浏览文件,在指定的行号获取字符串的长度,然后在到达该行(删除字符串)时使用该长度退格(并删除字符串),然后写入新数据吗?

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

最佳答案

如果您使用的是Java 7或更高版本,并且lineNumber从1开始,则可以执行以下操作:

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

显然,如果lineNumber从0开始,则:
lines.set(lineNumber, data);

09-28 04:09