文件内容指定替换与删除
原数据量
需要去除的内容
需要替换的内容
正式表lnk_scan_real_time_stock
临时表 lnk_scan_real_time_stock_temp
实现代码
package com.hand.demo;
import java.io.*;
/**
* 以文件格式
* 导出临时表大量数据后 (由于数据量很大,不能直接打开临时表文件
* 用一键替换的方式把临时表的表名改为正式表)
*
* 再插入正式表
*
* @author dujangzhou
* @date 2023/8/1 10:17
*/
public class Demo23 {
public static void main(String[] args) throws Exception {
File file = new File("D://ES//lnk_scan_real_time_stock_temp.sql");
operationFile(file);
}
public static void operationFile(File file) {
try {
InputStream is = new FileInputStream(file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String filename = file.getName();
// tmpfile为缓存文件,代码运行完毕后此文件将重命名为源文件名字。
File tmpfile = new File(file.getParentFile().getAbsolutePath()
+ "\\" + filename + ".sql");
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpfile));
//替换的目标字符串
String target = "lnk_scan_real_time_stock_temp";
// 替换的字符串
String newContent = "lnk_scan_real_time_stock";
boolean flag = false;
String str = null;
int i = 0;
while (true) {
str = reader.readLine();
i++;
if (str == null) {
break;
}
//删除指定行数据
if (i <= 69) {
System.out.println(str);
continue;
}
if (str.contains(target)) {
str = str.replace(target, newContent);
writer.write(str + "\n");
flag = true;
} else {
writer.write(str + "\n");
}
}
is.close();
writer.flush();
writer.close();
if (flag) {
file.delete();
tmpfile.renameTo(new File(file.getAbsolutePath()));
} else {
tmpfile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
实现后效果