java 更新文件内容吗,如何在Java中更新文本文件的某些部分

I want to be able to update a certain line on a text file.

But I get the error that it cannot delete the file, why do I get this error?

public class Main {

public static void main(String[] args) {

Main rlf = new Main();

rlf.removeLineFromFile("F:\\text.txt", "bbb");

}

public void removeLineFromFile(String file, String lineToRemove) {

try {

File inFile = new File(file);

if (!inFile.isFile()) {

System.out.println("Parameter is not an existing file");

return;

}

//Construct the new file that will later be renamed to the original filename.

File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

BufferedReader br = new BufferedReader(new FileReader(file));

PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

String line = null;

//Read from the original file and write to the new

//unless content matches data to be removed.

while ((line = br.readLine()) != null) {

if (!line.trim().equals(lineToRemove)) {

pw.println(line);

pw.flush();

}

}

pw.close();

br.close();

//Delete the original file

if (!inFile.delete()) {

System.out.println("Could not delete file");

return;

}

//Rename the new file to the filename the original file had.

if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file");

}

catch (FileNotFoundException ex) {

ex.printStackTrace();

}

catch (IOException ex) {

ex.printStackTrace();

}

}

}​

解决方案

The program works for me. Perhaps you are having an environmental issue.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值