0

I'm trying to remove an item from an Text file using an arrayList. The ArrayList get's its values from the Text File, and then it displays it in a ListView.

I have a contextual menu that pops up, and gives me an option to remove the item from the list.

In the text file, all the items are on a new line.

How will I go about removing specific items from the file? The ArrayList will clear it's self, and pull the data into the ArrayList when ever the action has been performed, so that is sorted.

Code to remove item from array:

                  int id = info.position;

              for(int i = array.size()-1; i >=0; i--){
                  array.remove(id);
              }
1
  • 2
    You cannot remove lines from a file. You will have to remove the lines in the ArrayList and then write back to the file. Commented Apr 12, 2014 at 14:04

2 Answers 2

1

File != ArrayList, ArrayList don't know anything about File and File don't know anything about ArrayList.

A way to do what you want is to rewrite again the data inside the file when you need it (when you delete an item from an ArrayList, call a method which updates the TextFile)

You should call it before ArrayList clear (or you will lose every value!)

An example:

List<String> values = new ArrayList<String>();
values.add("A");
values.add("B");
values.add("C");
values.add("D");
values.add("E");
values.add("D");

BufferedWriter fileWriter = null;
try
{
    fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("fileName.txt")));

    for (String value : values)
    {
        fileWriter.write(value + System.getProperty("line.separator"));
    }
}
finally
{
    if (fileWriter != null)
        fileWriter.close();
}

I think it's a safe way to do this without depend much to the fact that the file is not changed by another source (in any way)

Sign up to request clarification or add additional context in comments.

Comments

0

If each item in the ArrayList is equivalent to each line in the file, then just keep track of the index of the position of deleted item in the ArrayList. Then rewrite the entire file except that tracked index (which should be that same line).

Basically, once you delete the item from you ArrayList, then just write over the file as you loop through your updated ArrayList.

1 Comment

Thanks for the suggestion. I managed to get the index of the array item, however, if I try to remove the item from the ArrayList, I hat a dead end, as the item doesn't get removed from the arrayList. I added the code I'm using to my original post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.