954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

java-delete a file does not work

i got this code form the internet where it can delete a file.but when i tried to use it n my own java program it does not work anymore.it always returns 'Could not delete file'.
~this code is for my method delete

public void delete(String file, String lineToRemove) throws IOException{
                
     try {
          File inFile=new File("person.txt");
          if (!inFile.isFile()) {
          System.out.println("Parameter is not an existing file");
          return;
      }
      
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
      
      BufferedReader br = new BufferedReader(new FileReader(file));
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
      
      String line = null;

      while ((line = br.readLine()) != null) {
        
        if (!line.trim().equals(lineToRemove)) {

          pw.println(line);
          pw.flush();
        }
      }
      pw.close();
      br.close();
      
      //Delete the original file
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      } 
      
      //Rename the new file to the filename the original file had.
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");
      
    }
    catch (FileNotFoundException ex) {}
  }
public void run() throws IOException{
    File file=new File("person.txt");
    BufferedReader br=new BufferedReader(new FileReader(file));

    while((str=br.readLine())!=null)
        i++;
    
       System.out.print("\t\t\t\t\t\t***************WELCOME*****************");
       System.out.println();
       System.out.println("1. Add \n2. Edit \n3. Delete \n4. Exit");
       System.out.print("\nEnter option: ");
       option=in.next();
        
        while(true){
            ......
            else if(option.charAt(0)=='3'){
                FilingDatabase fd= new FilingDatabase();
                System.out.print("Enter word: ");
                String word=in.next();
                fd.delete("person.txt",word);
            }        
            ......
       }
    }


~any help would be most appreciated.
~nesnes

nesnes
Newbie Poster
3 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

to delete a file i always use

public void DeleteFile ()
    {

        File erase = new File ("Filename.txt");
        erase.delete ();  //deleting the file Statistics
        JOptionPane.showMessageDialog (infoPane, "The file has been deleted");
    }
scheppy
Junior Poster in Training
95 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

Does the write to the file succeed before you call the delete()? Perhaps the PrintWriter is still attached to inFile even after the close call?

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

to delete a file i always use

public void DeleteFile ()
    {

        File erase = new File ("Filename.txt");
        erase.delete ();  //deleting the file Statistics
        JOptionPane.showMessageDialog (infoPane, "The file has been deleted");
    }


still doesn't work:'(

nesnes
Newbie Poster
3 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

> i got this code form the internet where it can delete a file.but when i tried to use it n my own java program it does not work anymore.it always returns 'Could not delete file'.

First thing, never have empty catch blocks in your code, ever, no matter what. Second, your code doesn't handle special conditions where failure to close a stream will result in other streams remaining unclosed thereby leaking file handles. Third, if the file "person.txt" is opened in Excel or some other program, it will allow you to read data from it but block deletion since the file is already open by some other application.

For first point, make sure you always log exceptions or at the very least print stack trace. For the second point, if you are using Java 7, you can write:

try (BufferedReader in = new BufferedReader(new FileReader(f)); PrintWriter out = new PrintWriter(tmp)) {
    String s;
    while ((s = in.readLine()) != null) {
        out.print(s);
        System.out.println(s);
    }
}

And your streams will automatically be closed after the "try" block completes.

For third, make sure *no* other program is currently reading or has the given file open.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: