Java程序来删除一个文件中的某些文本
要从Java文件中删除某些文本,请看下面的代码片段-
示例
File input_file = new File("path to the .txt file");
File temp_file = new File("path to the .txt file");
BufferedReader my_reader = new BufferedReader(new FileReader(input_file));
BufferedWriter my_writer = new BufferedWriter(new FileWriter(temp_file));
String lineToRemove = "string to remove";
String current_line;
while((current_line = my_reader.readLine()) != null) {
String trimmedLine = current_line.trim();
if(trimmedLine.equals(lineToRemove)) continue;
my_writer.write(current_line + System.getProperty("line.separator"));
}
my_writer.close();
my_reader.close();
boolean is_success = temp_file.renameTo(input_file);输出结果
The input file’s specific string is deleted.
定义了两个文件,一个是输入文件,另一个是临时文件。创建一个缓冲的读取器和一个缓冲的写入器实例,并定义了需要从字符串中删除的字符串。迭代输入文件,遇到需要删除的字符串时,将其删除,并关闭读写器实例,如果此操作成功,则将输入文件的名称分配给临时文件。
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短