

{"id":101040,"date":"2022-04-26T09:00:21","date_gmt":"2022-04-26T03:30:21","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=101040"},"modified":"2026-05-30T16:40:35","modified_gmt":"2026-05-30T11:10:35","slug":"how-to-delete-file-in-java","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/","title":{"rendered":"How to Delete File in Java?"},"content":{"rendered":"<p>We have seen how to create a file and how to open a file, but there might be instances where we might require deleting a file as well. Java also has provisions for that. Unlike Create and Open, Java only has two methods to delete a file. In this article, we will discuss how to delete a file in Java.<\/p>\n<h3>Deleting a File in Java<\/h3>\n<p><strong>There are two ways to delete a file in Java:<\/strong><\/p>\n<ul>\n<li>Using the File.delete() method.<\/li>\n<li>Using the File.deleteOnExit() method.<\/li>\n<\/ul>\n<p>Let us discuss them at length.<\/p>\n<p>&nbsp;<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/initial-state-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-109135\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/initial-state-1.webp\" alt=\"initial state\" width=\"1147\" height=\"774\" \/><\/a><\/p>\n<p>Initially, we can see there are these two text files. We will delete them both using two different methods.<\/p>\n<h4>1. Using the Java File.delete() method<\/h4>\n<p>The File class in Java contains the File.delete() method can delete a file from the desired location. The delete() method can delete both files and directories, as long as the directory is empty. The files and directories are denoted by an abstract pathname in the method.<\/p>\n<ul>\n<li>The execution time of this method is fast. It deletes the object as soon as the method is called<\/li>\n<li>If the method is successful on deleting the object, it returns true; otherwise false.<\/li>\n<li>It deletes the files when the method is called.<\/li>\n<\/ul>\n<p><strong>The method signature of the Java File.delete() method is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public boolean delete()  \r\n<\/pre>\n<p>If the file\/directory is deleted, the method returns true else false.<\/p>\n<p><strong>Code to understand the File.delete() method in Java<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileDelete;\r\nimport java.io.File;\r\npublic class deleteMethod\r\n{\r\n    public static void main(String[] args)  \r\n        {     \r\n        try  \r\n        {         \r\n            File f_delete= new File(\"G:\\\\Internship\\\\File Delete\\\\DeleteMethod.txt\");      \r\n            if(f_delete.delete())                \r\n            System.out.println(\"Deletion Complete: \"+f_delete.getName()); \r\n            else  \r\n            System.out.println(\"Failed!!!!!\");  \r\n        }  \r\n        catch(Exception e)  \r\n        {  \r\n            e.printStackTrace();  \r\n        }  \r\n        }\r\n}\r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">Deletion Complete: DeleteMethod.txt<\/div>\n<div><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/deleteonexit-method.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108966\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/deleteonexit-method.webp\" alt=\"deleteonexit method\" width=\"1915\" height=\"1035\" \/><\/a><\/div>\n<div><\/div>\n<p>We can see that the desired file has been removed from the path.<\/p>\n<h4>2. Using the Java File.deleteOnExit() method<\/h4>\n<p>The File.deleteOnExit() method also works in the same way as the delete() method; the only difference is that this method deletes in reverse order. This method deletes the file when the JVM terminates. It does not return any value; once the deletion request is made, it cannot be reverted, so this method should be used carefully.<\/p>\n<ul>\n<li>It aligns the deletion of an object and executes automatically. There is no need to call this method explicitly.<\/li>\n<li>The deleteOnExit does not return any value.<\/li>\n<li>It marks the file that is going to be deleted.<\/li>\n<\/ul>\n<p><strong>The method signature of the Java File.deleteOnExit() method is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public void deleteOnExit()  \r\n<\/pre>\n<p>This method is generally used to delete temporary files of less importance, which should be deleted when terminating the JVM. If we want to delete a .temp file manually, we can always use the delete() method.<\/p>\n<p><strong>Code to understand the working of the deleteOnExit() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileDelete;\r\nimport java.io.File;  \r\nimport java.io.IOException;  \r\npublic class DeleteOnExitMethod\r\n{\r\n    public static void main(String[] args)  \r\n        {     \r\n            File f_delete= new File(\"G:\\\\Internship\\\\File Delete\\\\DeleteOnExitMethod.txt\");         \r\n            f_delete.deleteOnExit();                      \r\n            System.out.println(\"File exists : \" + f_delete.exists());  \r\n        }   \r\n}  \r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">File exists : true<\/div>\n<p>Since we did not exit the JVM, the file still exists. Now, if terminate the JVM and then run the code once again, the output will be:<\/p>\n<p>File exists : false<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/deletemethod-state.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108965\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/deletemethod-state.webp\" alt=\"deletemethod state\" width=\"1915\" height=\"1035\" \/><\/a><\/p>\n<p>So, we can see that the file is no longer there in the location, after terminating the JVM.<\/p>\n<p>We already discussed that the deleteOnExit() method is used for temp files in most cases. Let us see an example, how it works.<\/p>\n<p><strong>Code to understand the working of deleteOnExit() method on temp files:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileDelete;\r\nimport java.io.File;  \r\nimport java.io.IOException; \r\npublic class DeleteOnExitTemp\r\n{\r\n    public static void main(String[] args)  \r\n    {     \r\n        File temp;  \r\n        try  \r\n        {  \r\n            temp = File.createTempFile(\"temporay_file\", \".temp\");     \r\n            System.out.println(\"Temp file created at location: \" + temp.getAbsolutePath());      \r\n            temp.deleteOnExit();                      \r\n            System.out.println(\"Temp file status: \" + temp.exists());  \r\n        }   \r\n        catch (IOException e)  \r\n        {  \r\n            e.printStackTrace();  \r\n        }  \r\n    }   \r\n}  \r\n<\/pre>\n<p><strong>The output of the above code:<\/strong><\/p>\n<div class=\"code-output\">Temp file created at location: C:\\Users\\ARKAPC~1\\AppData\\Local\\Temp\\temporay_file7422334102278577407.temp<br \/>\nTemp file status: true<\/div>\n<p>So, the temporary file created using this program will be deleted on exiting the JVM.<\/p>\n<h3>Conclusion<\/h3>\n<p>In this article, we saw how to delete a file in Java using the two methods present in it. Deletion is essential for storage management. If the programmer keeps on creating and using files and does not delete any files, one day the storage will run out, so it is essential to manage the storage efficiently.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We have seen how to create a file and how to open a file, but there might be instances where we might require deleting a file as well. Java also has provisions for that.&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":108956,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[26821,36746,36744,36745,36743],"class_list":["post-101040","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-delete-file-in-java","tag-different-ways-to-delete-method-in-java","tag-file-delete-method-in-java","tag-file-deleteonexit-method-in-java","tag-how-to-delete-file-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Delete File in Java? - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn different ways to delete file in java like using the File.delete() method and using the File.deleteOnExit() method.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Delete File in Java? - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn different ways to delete file in java like using the File.delete() method and using the File.deleteOnExit() method.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-04-26T03:30:21+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-30T11:10:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Delete File in Java? - DataFlair","description":"Learn different ways to delete file in java like using the File.delete() method and using the File.deleteOnExit() method.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/","og_locale":"en_US","og_type":"article","og_title":"How to Delete File in Java? - DataFlair","og_description":"Learn different ways to delete file in java like using the File.delete() method and using the File.deleteOnExit() method.","og_url":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2022-04-26T03:30:21+00:00","article_modified_time":"2026-05-30T11:10:35+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"How to Delete File in Java?","datePublished":"2022-04-26T03:30:21+00:00","dateModified":"2026-05-30T11:10:35+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/"},"wordCount":607,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp","keywords":["delete file in java","different ways to delete method in java","File.delete() method in java","File.deleteOnExit() method in java","how to delete file in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/","url":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/","name":"How to Delete File in Java? - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp","datePublished":"2022-04-26T03:30:21+00:00","dateModified":"2026-05-30T11:10:35+00:00","description":"Learn different ways to delete file in java like using the File.delete() method and using the File.deleteOnExit() method.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/delete-a-file-in-java.webp","width":1200,"height":628,"caption":"delete a file in java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/how-to-delete-file-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"How to Delete File in Java?"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/101040","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=101040"}],"version-history":[{"count":8,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/101040\/revisions"}],"predecessor-version":[{"id":148545,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/101040\/revisions\/148545"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/108956"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=101040"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=101040"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=101040"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}