如何使用Java替换文件中的特定行?

时间:2015-07-13 05:31:17

标签: java filewriter printwriter

如何使用FileWriter和PrintWriter在文本文件中写入特定行?我不想每次都要制作新文件。

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

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 个答案:

答案 0 :(得分:4)

如果您使用的是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);