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 婚前女儿生日祝福语简短