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文件將包含中這個字段的整行數據刪除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.