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.
定义了两个文件,一个是输入文件,另一个是临时文件。创建一个缓冲的读取器和一个缓冲的写入器实例,并定义了需要从字符串中删除的字符串。迭代输入文件,遇到需要删除的字符串时,将其删除,并关闭读写器实例,如果此操作成功,则将输入文件的名称分配给临时文件。
热门推荐
9 庆双节祝福语简短
10 新年简短的祝福语爱情
11 老师出国祝福语大全简短
12 万寿祝福语简短
13 高考祝福语简短10字
14 发廊元旦祝福语大全简短
15 孩子16岁祝福语简短
16 宝宝周岁敬酒祝福语简短
17 生日宝宝祝福语简短独特
18 同事离别祝福语简短的