我的输入文件有很多记录,举个例子,假设它有(这里的行号仅供您引用)
1. end
2. endline
3. endofstory
我希望我的输出为:
1.
2. endline
3. endofstory
但是当我使用这段代码时:
import java.io.*;
public class DeleteTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File file = new File("D:/mypath/file.txt");
File temp = File.createTempFile("file1", ".txt", file.getParentFile());
String charset = "UTF-8";
String delete = "end";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
reader.close();
writer.close();
}
catch (Exception e) {
System.out.println("Something went Wrong");
}
}
}
我的输出为:
1.
2. line
3. ofstory
你们能帮我解决我期望的输出吗?
最佳答案
首先,您需要用新字符串 List item
替换该行,而不是空字符串。您可以使用 line = line.replace(delete, "List item");
来做到这一点,但是因为您只想在它是一行中唯一的字符串时才替换 end
你必须使用这样的东西:
line = line.replaceAll("^"+delete+"$", "List item");
根据您的编辑,您似乎确实要将包含 end
的行替换为空字符串。你可以使用这样的东西来做到这一点:
line = line.replaceAll("^"+delete+"$", "");
这里,replaceAll
的第一个参数是一个正则表达式,^
表示字符串的开始,$
表示结束。仅当 end
是该行中唯一的东西时,它才会被替换。
您还可以检查当前行是否是您要删除的行,然后只向文件写入一个空行。
例如:
if(line.equals(delete)){
writer.println();
}else{
writer.println(line);
}
要对多个字符串执行此过程,您可以使用如下内容:
Set<String> toDelete = new HashSet<>();
toDelete.add("end");
toDelete.add("something");
toDelete.add("another thing");
if(toDelete.contains(line)){
writer.println();
}else{
writer.println(line);
}
这里我使用了一组我想删除的字符串,然后检查当前行是否是这些字符串中的一个。
关于java - 如何使用java删除文本文件中的特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832915/