How to delete a jar file opened using URL#openConnection()?
<p>I have a small function which essentially takes a java.net.URL, reads the file and closes it. I want to delete the file after the read is over. However, I am not able to delete it even through the windows explorer, while the process is running. I get the error message that the file is still in use. This works good for normal files but not for jar files. Am I supposed to do something different? Here is the code snippet I am using.  </p>

<p>Updated code snippet:</p>

<pre><code>public static void tryPreOpenConnection(URL url, File file) throws IOException {
    URLConnection connection = url.openConnection();
    InputStream stream = connection.getInputStream();
    stream.read();
    stream.close();
    System.out.println("Deleted: " + file.delete());
    connection = null;
    stream = null;
    System.gc();
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
     // do nothing
    }
    System.out.println("Deleted: " + file.delete());
}
</code></pre>
