I wanted to know how I can remove items in an ArrayList, which are stored in an external text file. I am trying the Iterator method but I do not think I am doing it correctly.
This is the arraylist, which basically contains the text file of responses
This is the method, which allowed a txt file to hold an ArrayList of responses
public void writeAList(ArrayList<String> list, String filename)
{
if(list != null) {
try (FileWriter writer = new FileWriter(filename, true)) {
for(String item : list) {
writer.write(item.trim());
writer.write(" ");
}
writer.write("\n");
}
catch(IOException e) {
System.out.println("Problem writing file: " + filename +
" in writeAList");
}
}
else {
System.out.println("Null list passed to writeAList.");
}
}
This is the method that allows to read from it
public ArrayList<String> readAList(String filename)
{
ArrayList<String> list = new ArrayList<>();
try (BufferedReader reader =
new BufferedReader(new FileReader(filename))) {
String line = reader.readLine();
while(line != null) {
list.add(line.trim());
line = reader.readLine();
}
}
catch(IOException e) {
System.out.println("Problem reading file: " + filename +
" in readAList");
}
return list;
}
I assigned an ArrayList called like this
notRecognised = help.readAList("missed.txt");
And I tried to write the below method to be able to remove responses from the text file, but I do not think I have written it correctly.
public String removeResponse(ArrayList<String> words)
{
Iterator<String> it = words.iterator();
while(it.hasNext()) {
String word = it.next();
String response = notRecognised.get(word);
if(response.equals (words)) {
it.remove();
}
}
}
Text files only store text. If you want to edit it (remove items), you have to rewrite it. A more suitable data storage for CRUD (creation, retrieval, update, delete) of data would be using a database, not a text file.
You can read up here: JDBC Database Access