Deleting a file in Java <p>I want to delete a file, and sometimes I can, sometimes I don't. I'm doing this:</p> <pre><code>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"); } </code></pre> <p>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 <code>FileInputStream</code> or the <code>BufferedReader</code>? Because if I use those classes, I can't see if the file exists. Or can I?</p> <p><strong>Edit:</strong> I just found my error. I was doing this:</p> <pre><code>XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(filePath)); </code></pre> <p>and then, closing just the <code>eventWriter</code> .</p> <p>And I have to do this:</p> <pre><code>FileOutputStream fos = new FileOutputStream(filePath); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(fos); </code></pre> <p>and then:</p> <pre><code> eventWriter.close(); fos.close(); </code></pre>