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.
定义了两个文件,一个是输入文件,另一个是临时文件。创建一个缓冲的读取器和一个缓冲的写入器实例,并定义了需要从字符串中删除的字符串。迭代输入文件,遇到需要删除的字符串时,将其删除,并关闭读写器实例,如果此操作成功,则将输入文件的名称分配给临时文件。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下