如何从java中的文件中删除字符串 [英] How to delete a string from a file in java

查看:353
本文介绍了如何从java中的文件中删除字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本(Rachel),我想在该文件中搜索该用户,如果找到,则实际删除Rachel的记录。现在,我尝试了一些东西,但由于某种原因,代码没有删除用户Rachel。有人可以帮帮我吗?谢谢





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? Thanks


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

}

推荐答案

在o / s中很少次和/或编程语言,我是否能够简单地从文件中删除一行



通常,你做什么(取决于文件的大小)是读取行,操作它们(包括'跳过'你不想替换的行,即删除,并将它们写入(另一个)文件 - 有时更容易将它们写入临时文件,直到你完成,然后删除原始文件并将临时文件重命名为您应该拥有的文件(更安全,如果出现任何问题,您仍然有数据副本)


$ b在你的情况下$ b,你可以从你拥有的文件中读取,但是创建一个FileWriter并写入Textsave.Txt.Tmp,也就是说,你将所有行写入'.Tmp'版本除了行(s) )你已经确定需要删除
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


我要首先要强调的是n在程序之上,文件在读取模式下打开,这将不允许用户修改文件。



为了达到同样的目的,你可以使用RandomAccessFile,但它是of Java 7

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





仍然会给出理想的解决方案加斯先生。总是很好地将所需内容复制到一个临时文件中,删除现有文件,然后将临时文件重命名为原始文件。

问候,

panduranga。
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.


这篇关于如何从java中的文件中删除字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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