package tool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* 读取txt文件,文件中有多个字段信息 读取一个字段信息,到对应的csv文件中删除这个字段信息所在的那行数据
*
* @author sunhongbin
*/
public class Tool {
public static void main(String[] args) throws IOException {
String key, line;
String path = "E:/DataSet/runRes";
int count = 0;
boolean isExists = false;
ArrayList<String> msgList = new ArrayList<>();
// 关联路径,删除信息存放的文件
File msgFile = new File(path + "/missed.txt");
InputStreamReader msgReader = new InputStreamReader(new FileInputStream(msgFile), "UTF-8");
BufferedReader br = new BufferedReader(msgReader);
while ((key = br.readLine()) != null) {
msgList.add(key);
}
br.close();
// 关联路径,要做修改的文件
File recordFile = new File(path + "/record.csv");
InputStreamReader recordReader = new InputStreamReader(new FileInputStream(recordFile), "UTF-8");
BufferedReader br2 = new BufferedReader(recordReader);
while ((line = br2.readLine()) != null) {
count++;
for (String item : msgList) {
if (line.indexOf(item) != -1) {// 说明存在字段,该行不能要
isExists = true;
System.out.println("第" + count + "行被删除");
break;
} else {
isExists = false;
}
}
if (isExists == false) {
createAndWrite(path, line);
}
}
}
public static void createAndWrite(String filePath, String msg) throws IOException {
/**
* 生成一个文件后往文件里写入内容
*/
File dir = new File(filePath);
if (!dir.exists()) { // 检查是否存在该路径,没有的话创建路径
dir.mkdirs();
}
// 关联文件,检查是否已经有该文件,没有的话在创建
File file = new File(filePath + "/replace.csv");
if (!file.exists()) {
boolean isCreate = file.createNewFile();
if (isCreate) {
System.out.println("创建成功");
} else {
System.out.println("创建失败");
}
}
FileWriter writer = null;
try {
writer = new FileWriter(file, true);
writer.append(msg + "\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
}
读取文本文件,文件中有多个字段信息 读取一个字段信息,到对应的csv文件将包含中这个字段的整行数据删除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.