Deleting a file using the delete () method in Java

I doubt the following code a bit:

try { File file = new File("writing"); file.createNewFile(); System.out.println(file.delete()); System.out.println(file.exists()); PrintWriter pw = new PrintWriter(file); pw.print(324.2342); pw.flush(); pw.close(); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); System.out.println(br.readLine()); br.close(); } catch(IOException ioE) { System.out.println("Indeed"); } 

Why, in this case, the file.delete () method seems to say that it works when it returns true when it is executed, and it is also confirmed by the file.exists() method, which returns false. However, at runtime, I do not get any exceptions, such as "IOException file" writing "does not exist" or something like that.

Why does the file remain on the heap although physically deleted? Shouldn't garbage be collected automatically as soon as the delete method is called? I know that this is not because I saw the result.

+6
source share
4 answers

This is because File represents an abstract path, see the JavaDoc for it http://docs.oracle.com/javase/6/docs/api/java/io/File.html . It is not a file descriptor in the OS.
Line in your code:

 PrintWriter pw = new PrintWriter(file); 

Just creates a new file. Try deleting the file after calling this ...

+4
source

File object is the path to a physical file in the file system either exists or not. That is why you have exists() (to check if it exists) and createNewFile() (to create a file if it is not found).


Also note that PrintWriter(File file) creates a new file if it does not exist.

Options:

file - A file to use as the destination for this author. If the file exists, then it will be truncated to zero size; otherwise a new file will be created. The output will be written to a file and there will be a buffer.

+2
source

A file is a handle to a real file (whether it exists or not). You create and then delete the file above, as you say, everything is still there.

When you come to PrintWriter later, it will create the file again when you use it - it doesn't matter that you deleted it before.

In fact, depending on your use case, it may be unconditional what you want - you can, for example, delete the old log file before re-creating and writing it again.

Finally, nothing in your code will have the right to garbage collection until your method exists, and even then the underyling file will continue to exist (unless you delete it) - and any garbage collector in this case will not affect base file. It will be deleted after the delete call and will exist again after you do PrintWriter with it.

Hope this helps!

+1
source

The file does not have a link to a specific file, and not to any pointer to a file along the path to the file. Using this line, you create a new file:

 PrintWriter pw = new PrintWriter(file); 
0
source

All Articles