-2

I have two files one contains data and another contains the string. My target is to read the file containing string and see if that string exist in data file and delete that whole row.

Sample data would be :

Data file :

Name='Raj' Age='25' Location='India'

Name='Suresh' Age='26' Location='India'

String file contain : Raj

So when it parse the data file it should delete the first line from data file.

1 Answers1

0

This is not so difficult, and you haven't post what you have tried. However I am posting a solution for your reference. You can modify/optimize it as per your requirement.

1. First Create a method -

private List<String> getFileContentList(String filePath) {
    List<String> list = new ArrayList<String>();
    try {
        String line;
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

2. Now do something like below -

List<String> dataList = getFileContentList("C:/DataFile.txt");
List<String> keyList = getFileContentList("C:/KeyFile.txt");        

for (String string1 : keyList) {
    for (int i = 0; i < dataList.size(); i++) {
        if(dataList.get(i).contains(string1)) {
            dataList.remove(i);
        }
    }
}

FileWriter fw;
try {
    fw = new FileWriter("C:/DataFile.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        for (String string : dataList) {
            bw.write(string);
            bw.newLine();
        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
Kartic
  • 2,935
  • 5
  • 22
  • 43