

{"id":101030,"date":"2022-04-27T09:00:26","date_gmt":"2022-04-27T03:30:26","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=101030"},"modified":"2026-05-30T16:22:38","modified_gmt":"2026-05-30T10:52:38","slug":"how-to-create-a-file-in-java","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/","title":{"rendered":"How to Create a File in Java?"},"content":{"rendered":"<p>A file in Java can be created by importing the file class from the java input output package. By creating the file in java, you can perform various operations on it. Files that are created using Java keep the information also when the execution of a program ends. Thus, storing the data permanently on the hard disk of a device.<\/p>\n<p>Files are an integral part of everyone\u2019s life, not just for programmers but also normal users. Files can be used to store, organize and edit data. In java, creating a file is easier than one can imagine. There are three ways in which we can create a file in Java. In this article, we will take a look at all those methods at length.<\/p>\n<h3>Different ways to create a file in Java<\/h3>\n<p>Java has various predefined classes and packages that contain methods to make creating files as simple as it can get. There are three methods to create a file in Java, they are as follows:<\/p>\n<ul>\n<li>By Using File.createNewFile() method<\/li>\n<li>Using FileOutputStream class<\/li>\n<li>By Using File.createFile() method<\/li>\n<\/ul>\n<p>Let us discuss them one by one.<\/p>\n<h4>1. Using File.createNewFile() method in java<\/h4>\n<p>The File.createNewFile() method is part of the File class of the java.io package. The method doesn\u2019t accept any arguments and has a return type of boolean. It returns true if the file is created and false if the file with the same name already exists.<\/p>\n<p>The File.createNewFile() also throws I\/O Exception if there is an exception during the creation of the file. It can also throw a SecurityException if the system has a security manager. Its SecurityManager.checkWriter(java.lang.String) method denies write access to the file.<\/p>\n<p>We have to provide the file name and absolute or relative path of the file while creating the File object. If no path is mentioned the file is created in the PWD(Present Working Directory).<\/p>\n<p><strong>The signature of the method is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public boolean createnewFile() throws IOException\r\n<\/pre>\n<p><strong>Code to understand the working of File.createNewFile() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileCreation;\r\nimport java.io.*;\r\npublic class createNewFile_Method\r\n{\r\n    public static void main(String[] args)   \r\n    {     \r\n        File file_create = new File(\"G:\\\\Internship\\\\File Creation\\\\NewTextFile1.txt\");\r\n        boolean success;  \r\n        try   \r\n        {  \r\n            success = file_create.createNewFile();\r\n        if(success)  \r\n        {  \r\n            System.out.println(\"The File \"+file_create.getCanonicalPath()+\" is created!!!\"); \r\n        }  \r\n        else  \r\n        {  \r\n            System.out.println(\"The File already exist at location: \"+file_create.getCanonicalPath());  \r\n        }  \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\">The File G:\\Internship\\File Creation\\NewTextFile1.txt is created!!!<\/div>\n<div><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/createnewfile.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108969\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/createnewfile.webp\" alt=\"createnewfile\" width=\"1919\" height=\"1031\" \/><\/a><\/div>\n<p>So, from the above image, it is clear that the file has been created successfully.<\/p>\n<p><strong>Explanation<\/strong><\/p>\n<p>1. We first create a File class object, here I have given it the name file_create, you can give any name.<\/p>\n<p>2. Now we create a boolean variable that will store the return value of the createNewFile() method.<\/p>\n<p>3. Now we check if the result is true or false. If it is true that means the file is created, otherwise, the file was not created.<\/p>\n<p>4. We use the try-catch block to handle the exception thrown by the method.<\/p>\n<h4>2. Using the FileOutputStream class in Java<\/h4>\n<p>The FileOutputStream class is part of the java.io package. It is generally used to write in a file. However, if the file doesn\u2019t exist in the mentioned path, a file by the given name is created for the purpose of writing in it. The FileOutputStream class provides a constructor that is used to create and write in a file.<\/p>\n<p><strong>The function signature of the constructor is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public FileOutputStream(String name, boolean append) throws FileNotFoundException  \r\n<\/pre>\n<p>The Parameter name contains the file name and the parameter append will write at the end of the file if its value is true, and if it is false it will write at the beginning.<\/p>\n<p><strong>Code to understand the working of FileOutputStream class:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileCreation;\r\nimport java.io.*;\r\nimport java.util.*;\r\npublic class FileOutputStream_class\r\n{\r\n    public static void main(String args[])  \r\n    {  \r\n        try  \r\n        {  \r\n            Scanner sc=new Scanner(System.in);\r\n            System.out.print(\"Enter the file name: \");  \r\n            String fname=sc.nextLine();               \r\n            FileOutputStream file_create=new FileOutputStream(fname, true);  \r\n            System.out.print(\"Enter the content of the file: \");         \r\n            String str=sc.nextLine()+\"\\n\";     \r\n            byte[] b= str.getBytes();       \r\n            file_create.write(b);           \r\n            file_create.close();           \r\n            System.out.println(\"File is saved in the given location!!!!\");  \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\">Enter the file name: G:\\Internship\\File Creation\\NewTextFile2.txt<br \/>\nEnter the content of the file: This file is created with FileOutputStream class<br \/>\nFile is saved in the given location!!!!<\/div>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/fileoutputstreamclass.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108970\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/fileoutputstreamclass.webp\" alt=\"fileoutputstreamclass\" width=\"1919\" height=\"1031\" \/><\/a><\/p>\n<p>From the above image, we can see that the file is created in the given location successfully.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/file-at-location.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108971\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/file-at-location.webp\" alt=\"file at location\" width=\"1919\" height=\"1031\" \/><\/a><\/p>\n<p>This image shows the content of the file.<\/p>\n<p><strong>Explanation:<\/strong><br \/>\n1. We use the utility scanner to take input from the user regarding the name of the file and its content.<\/p>\n<p>2. We then create an object of the FileOutputStream class and pass the argument with the file name and true\/false as per our requirement.<\/p>\n<p>3. After that, we enter the content of the file.<\/p>\n<p>4. Then the content is converted to bytes, as FileOutputStream is a byte stream.<\/p>\n<p>5. We then write the bytes onto the file and close it.<\/p>\n<p>6. The whole thing is done inside a try-catch block to handle the exceptions thrown.<\/p>\n<h4>3. Using File.createFile() method in Java<\/h4>\n<p>The File.createFile() is a method that is part of the File class of the java.nio package. The nio package is a buffer-oriented package. It also provides support for files. The method createFile() creates a new and empty file. Unlike other methods, the resources need not be closed in this method.<\/p>\n<p><strong>The signature of this method is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public static Path createFile(Path, Attribute) throws IOException  \r\n<\/pre>\n<p>The path parameter is to enter the path of the file and the attribute method is to enter an optional list of file attributes.<br \/>\nThe method returns the created file.<\/p>\n<p>Before writing the code, one particular line requires some information:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Path path = Paths.get(\"G:\\\\Internship\\\\File Creation\\\\NewTextFile3.txt\");\r\n<\/pre>\n<p>In the above line of code, Path is an interface and Paths is a class. The Paths.get() method creates an instance of Path and is given the name path.<\/p>\n<p><strong>Code to understand the working of File.createFile() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">package com.DataFlair.FileCreation;\r\nimport java.nio.file.*;\r\nimport java.io.*;\r\npublic class createFile_Method\r\n{\r\n    public static void main(String[] args)   \r\n    {  \r\n        Path path = Paths.get(\"G:\\\\Internship\\\\File Creation\\\\NewTextFile3.txt\"); \r\n        try   \r\n        {  \r\n            Path file_path= Files.createFile(path); \r\n            System.out.println(\"File Created at \"+file_path+\" Successfully!!!\");  \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\">File Created at G:\\Internship\\File Creation\\NewTextFile3.txt Successfully!!!<\/div>\n<div><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/createfile-method.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-108972\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/createfile-method.webp\" alt=\"createfile method\" width=\"1903\" height=\"1031\" \/><\/a><\/div>\n<p>From the above image, we can see that the file is created in the given location successfully.<\/p>\n<p><strong>Explanation<\/strong><\/p>\n<p>1. At first, we create the Path instance.<br \/>\n2. The file is created using the createFile() method in the specified location.<br \/>\n3. We use the try-catch block to handle the exception.<\/p>\n<h3>Conclusion<\/h3>\n<p>So, in this article, we saw how we can create a file fairly easily using java. The methods provided by Java make file creating really simple. It also gives the programmer an option to choose from the various methods it has. So, making the job of the programmer easy and simple.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A file in Java can be created by importing the file class from the java input output package. By creating the file in java, you can perform various operations on it. Files that are&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":108958,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[26822,36734,36732,36733],"class_list":["post-101030","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-create-file-in-java","tag-different-methods-to-create-a-file-in-java","tag-different-ways-to-create-file-in-java","tag-how-to-create-a-file-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Create a File in Java? - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn different ways to create file in java like Using File.createNewFile() method, FileOutputStream class and File.createFile() 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-create-a-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 Create a File in Java? - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn different ways to create file in java like Using File.createNewFile() method, FileOutputStream class and File.createFile() method.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/how-to-create-a-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-27T03:30:26+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-30T10:52:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-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=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Create a File in Java? - DataFlair","description":"Learn different ways to create file in java like Using File.createNewFile() method, FileOutputStream class and File.createFile() 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-create-a-file-in-java\/","og_locale":"en_US","og_type":"article","og_title":"How to Create a File in Java? - DataFlair","og_description":"Learn different ways to create file in java like Using File.createNewFile() method, FileOutputStream class and File.createFile() method.","og_url":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2022-04-27T03:30:26+00:00","article_modified_time":"2026-05-30T10:52:38+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-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":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"How to Create a File in Java?","datePublished":"2022-04-27T03:30:26+00:00","dateModified":"2026-05-30T10:52:38+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/"},"wordCount":978,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-file-in-java.webp","keywords":["create file in java","different methods to create a file in java","different ways to create file in java","how to create a file in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/","url":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/","name":"How to Create a File in Java? - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-file-in-java.webp","datePublished":"2022-04-27T03:30:26+00:00","dateModified":"2026-05-30T10:52:38+00:00","description":"Learn different ways to create file in java like Using File.createNewFile() method, FileOutputStream class and File.createFile() method.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-file-in-java\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-file-in-java.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2022\/04\/create-file-in-java.webp","width":1200,"height":628,"caption":"create file in java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/how-to-create-a-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 Create a 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\/101030","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=101030"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/101030\/revisions"}],"predecessor-version":[{"id":148539,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/101030\/revisions\/148539"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/108958"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=101030"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=101030"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=101030"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}