要从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.
定义了两个文件,一个是输入文件,另一个是临时文件。创建一个缓冲的读取器和一个缓冲的写入器实例,并定义了需要从字符串中删除的字符串。迭代输入文件,遇到需要删除的字符串时,将其删除,并关闭读写器实例,如果此操作成功,则将输入文件的名称分配给临时文件。