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

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

}

}

}

}

解决方案

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值