Jump to content

How TO Create File in Java


Recommended Posts

Whenever the data is need to be stored, a file is used to store the data. File is a collection of stored information that are arranged in string, rows, columns and lines etc.

In this section, we will see how to create a file. This example takes the file name and text data for storing to the file.

 

For creating a new file File.createNewFile( ) method is used. This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true.

 

Lets see an example that checks the existence of  a specified file.

 

import java.io.*;

 

public class CreateFile1{

   public static void main(String[] args) throws IOException{

     File f;

     f=new File("myfile.txt");

     if(!f.exists()){

     f.createNewFile();

     System.out.println("New file \"myfile.txt\" has been created

                         to the current directory");

     }

   }

}

 

 

irst, this program checks, the specified file "myfile.txt" is exist or not. if it does not exist then a new file is created with same name to the current location.

 

Output of the Program

C:\nisha>javac CreateFile1.java

 

C:\nisha>java CreateFile1

New file "myfile.txt" has been created to the current directory

 

C:\nisha>

 

If you try to run this program again then after checking the existence of the file, it will not be created and you will see a message as shown in the output.

 

C:\nisha>javac CreateFile1.java

 

C:\nisha>java CreateFile1

The specified file is already exist

 

C:\nisha>

 

download program from here --> http://www.4shared.com/file/218606481/4eb368ec/CreateFile1.html

 

If I Put It On Wrong Section Trasfer It Thnx

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock