如何使用Java替换文件中的特定行? [英] How to replace a specific line in a file using Java?

查看:554
本文介绍了如何使用Java替换文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

如果您使用的是Java 7或更高版本,并且lineNumber从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);
}

很明显,如果lineNumber从0开始,则:

Obviously if lineNumber starts in 0, then:

lines.set(lineNumber, data);

这篇关于如何使用Java替换文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆