如何删除文本文件中的特定字符串? [英] How to delete a specific string in a text file?

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

问题描述

如何删除文本文件中的特定字符串?

解决方案

找到文件。
$ b

  File file = new File(/ path / to / file.txt); 

创建一个临时文件(否则你必须首先读入Java内存的所有内容)。 >

  File temp = File.createTempFile(file,.txt,file.getParentFile()); 

确定字符集。

  String charset =UTF-8; 

确定要删除的字符串。

  String delete =foo; 

打开文件阅读。

<$ p新的InputStreamReader(新的FileInputStream(文件),字符集)); $ p> BufferedReader reader = new BufferedReader

打开临时文件进行写入。



<$ printWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp),charset));

逐行读取文件



<$ (String line;(line = reader.readLine())!= null;){
// ...
}
code>

删除行中的字符串。

  line = line.replace(delete,); 

将其写入临时文件。

  writer.println(line); 

关闭读写器(最好在>

  reader.close(); 
writer.close();

删除文件。

  file.delete(); 

重命名临时文件。

  temp.renameTo(文件); 



另请参阅:




How can I delete a specific string in a text file?

解决方案

Locate the file.

File file = new File("/path/to/file.txt");

Create a temporary file (otherwise you've to read everything into Java's memory first).

File temp = File.createTempFile("file", ".txt", file.getParentFile());

Determine the charset.

String charset = "UTF-8";

Determine the string you'd like to delete.

String delete = "foo";

Open the file for reading.

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));

Open the temp file for writing.

PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));

Read the file line by line.

for (String line; (line = reader.readLine()) != null;) {
    // ...
}

Delete the string from the line.

    line = line.replace(delete, "");

Write it to temp file.

    writer.println(line);

Close the reader and writer (preferably in the finally block).

reader.close();
writer.close();

Delete the file.

file.delete();

Rename the temp file.

temp.renameTo(file);

See also:

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

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