user2144555
user2144555

Reputation: 1313

Deleting a file in Java

I want to delete a file, and sometimes I can, sometimes I don't. I'm doing this:

String filePath = "C:\\Users\\User\\Desktop\\temp.xml";
File f = new File(filePath);
if (f.exists())
{
  if(f.delete())
     System.out.println("deleted");
  else
     System.out.println("not deleted");
}

I think that when I can't delete it is because it is still open somewhere in the Application. But how can I can I close it, if I don't use the FileInputStream or the BufferedReader? Because if I use those classes, I can't see if the file exists. Or can I?

Edit: I just found my error. I was doing this:

XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(filePath));

and then, closing just the eventWriter .

And I have to do this:

FileOutputStream fos = new FileOutputStream(filePath);
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(fos);

and then:

    eventWriter.close();
    fos.close();

Upvotes: 0

Views: 138

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

I suggest to use NIO2 Files.delete which throws an IOException that explains why the file could not be deleted.

Upvotes: 1

Puce
Puce

Reputation: 38152

The file might be open by another process, you might not have sufficient rights to delete the file,...

Edit:

I also strongly recommend to use Automatic Resource Management wherever possible, to make sure your streams/ readers/ writers get properly closed.

Upvotes: 1

user2277872
user2277872

Reputation: 2973

If you're using the BufferedReader class, you can't check for the existence, thats what the File class is for. You can just open/close the file using BufferedReader, and check with File. Here is an example:

String filePath = "C:\\Users\\User\\Desktop\\temp.xml";
File f = new File(filePath);
if (f.exists())
{
   BufferedReader open = new BufferedReader(new FileReader(f));  // opens file
   open.write("blah");  //writes to file
   open.close();   // closes file
} else {
    System.out.println("File cannot be found");
}

Hopefully that helps you understand the situations a bit more!

Upvotes: 0

Related Questions