java删除文件字符,如何从java中的文件中删除字符串

I have a text("Rachel") and i want to search for that user in that file and if found then actually delete the record of Rachel. Now, i tried something but for some reason the code is no deleting the user Rachel. Can anyone please help me out? Thanksimport java.io.*;

import java.util.*;

public class trial {

public static void main(String args[]) throws IOException

{

FileReader fr = new FileReader("Textsave.txt");

BufferedReader br = new BufferedReader(fr);

String line = null;

String delete = "Rachel";

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

{

if(line.contains(delete))

{

System.out.println("Found");

System.out.println(line);

line.replace(delete, "");

}

}

br.close();

}

}

解决方案

very few times in an o/s and/or programming language, do I see the ability to simply delete a line from a file

usually, what you do (depending on the size of the file) is read the lines, manipulate them (including 'skip' the ones you don't want to replace, ie delete, and write them out to a(nother) file - its sometimes easier to write them out to a temporary file until your finished, then delete the original file and rename the temporary one to the file you're supposed to have (its safer, if anything goes wrong you still have a copy of the data)

in your case, you could read from a file like you have, but create a FileWriter and write to "Textsave.Txt.Tmp", that is, you write all lines to the '.Tmp' version except the line(s) you have identified as needing to be removed

The first thing i would like to highlight in above program, file is opened in Read Mode, this will not allow user to modify the file.

To achieve the same you can use RandomAccessFile , but it is part of Java 7

http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

Still the ideal solution will be given by Mr. Garth. Instead of over-writing the existing file it is always good copy the required contents in one temp file , delete the existing file, and then rename the temp file to original file.

Regards,

panduranga.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值