How to Create a File in Java Programming

0 Flares 0 Flares ×

Description

Creating a file in Java is extremely easy. To create a file in Java we use File.createNewFile() method which returns a boolean value true if the file is created and false if the file is already existing or the the file creation operation fails.

Parameters

No Parameters supplied.

Return Value

boolean: ‘true’ or ‘false’

  • true: if file created successfully
  • false: if file is already existing or the operation fails due to any reason

Exceptions

  • IOException: If any I/O error occurs
  • SecurityException: If write access to the disk is denied.

Example

Below is an example Java code to create a file on the disk.

package com.lessonslab.io.file;

import java.io.File;
import java.io.IOException;

public class CreateAFileInJava
{
public static void main(String[] args)
{
//Initialize the location of the file
String fileLoc = "c:\\mytestfile.txt";
//Create a new File Object
File myFile = new File(fileLoc);
try
{
//Physically the file is created and simultaneously we are checking the
//returned result from the method createNewFile()
if(myFile.createNewFile())
{
System.out.println("My New File Created.");
}
else
{
System.out.println("File already exists.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Above example will output : My New File Created if the operation is Successful else it will return File already Exists. Hope this tutorial helped you.

Guru

+Ayodhyanath Guru holds a B.Tech degree in Electrical Engineering and has worked with various prestigious clients in the IT industry and presently working as a Software Engineer. He is a part time blogger and presently authors the Jafaloo.Com blog. Being a tech enthusiast Guru likes to surf the web and blogs about interesting technical topics like How-To guides, freewares, Tutorials, Software, Gadgets, web applications etc. Apart from blogging he likes coding in Java/J2EE and PHP.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 0 Flares ×