gazza
gazza

Reputation: 1

How would i delete data from an external file?

The format i have in the external file is

name
tel no
mob no
address

From the gui i would like to delete a contact which is in the format of above using my delete button.

i have completed the export method and was wondering if deleting would be similar,, here is my code for exporting.

 {
   FileOutputStream file; 
   PrintStream out; 

   try {   file = new FileOutputStream("../files/example.buab", true);   
          out = new PrintStream(file);       
          out.println(txtname.getText());      
          out.println(txtnum.getText());     
          out.println(txtmob.getText());
          out.println(txtadd1.getText()); 

          System.err.println ("");                    
          out.close();              
       }            
          catch (Exception e)
                {                   
                 System.err.println ("Error in writing to file");          
                }
   }

Upvotes: 0

Views: 197

Answers (3)

BalusC
BalusC

Reputation: 1108782

Easiest way is to read it fully, skip the lines which are supposed to be deleted and then write it fully back to the file, hereby overwriting the original one. But that's also the least efficient way. For best results, you need to organize your data more in a model.

Why don't you use a (embedded) database instead so that you can just go ahead with a simple SQL DELETE statement?

Upvotes: 0

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

I assume you really have to use a file and cannot use a table in a database.

First of all you will have to assign an id to each contact, so that you can point to a certain contact, the id must be unique other than that it can be everything.

Why not organizing that file as an xml? Is this something your spec allows?

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114787

Do you really have to delete the contact on the file immediatly?

Usually you would do something like this:

  1. Import the file content into your model, iaw a list of Contact objects
  2. Apply all your edits to the model (change values, add a contact, delete a contact)
  3. Save your edits, iaw overwrite the file with your model.

Much, much easier then trying to delete a single row on a file...

Upvotes: 1

Related Questions