Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java File.createNewFile() Method
2.1.
Example
2.2.
Creating a new file:
2.3.
Creating a file, when it's already present:
3.
Java FileOutputStream Class
3.1.
Example
3.2.
Output
4.
Java File.createFile() method
4.1.
Example
4.2.
Output
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Creation of Files in Java

Author Pankhuri Goel
2 upvotes
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

A file is an abstract path that does not exist in the physical world. The underlying physical storage is only accessed while "using" that file. When a file is created indirectly, an abstract path is also established. The file is one method of storing data according to requirements.

Inbuilt files and functions are needed to create a new file, which will almost certainly throw Exceptions. As a result, we'll use Exception Handling Techniques to cope with it. One of these, known as the try-catch block approach, will be used here.

Creating a file in Java is simple because we use predefined classes and packages. A file can be made using one of these three methods.

  • using File.createNewFile() method
  • using FileOutputStream class
  • Using File.createFile() method

Also See, Multithreading in java, and Duck Number in Java.

Java File.createNewFile() Method

The File.createNewFile() method is a member of the java.io package's File class. It does not recognise any arguments. The technique produces a new, empty file on its own. It is used when the file is not already in physical existence. The method returns a boolean result of true or false:

  • true if the file was successfully created.
  • If the file already exists, return false.

We supply the file name when we initialise the File class object, and then we may call the File class's createNewFile() method to create a new file in Java.

If an I/O error occurs, the File.createNewFile() method throws java.io.IOException. If a security manager is present and its SecurityManager.checkWriter(java.lang.String) function prohibits write access to the file, it will throw a SecurityException. 

The method's signature is as follows:

public boolean createNewFile() throws IOException  

We can pass the file name, absolute path, or relative path in the File class object as an argument. For a non-absolute path, the File object tries to locate the file in the current directory.

Example

import java.io.File;
import java.io.IOException;
public class fc_example1
{
    public static void main(String[] args)
    {
        File file = new File("C:\\Users\\panis\\samplefile.txt"); //initialize File object and passing path as argument
        boolean result;
        try
        {  
            result = file.createNewFile(); //creates a new file
            if(result) 
            {
                System.out.println("File created "+file.getCanonicalPath()); //returns the path string
            }
            else
            {
                System.out.println("File already exists at location: "+file.getCanonicalPath());
            }
        }
        catch (IOException e)
        {
            e.printStackTrace(); 
        }
    }
}

Creating a new file:

Creating a file, when it's already present:

Must Read: Java System Out Println

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Java FileOutputStream Class

The data is written to a file by the FileOutputStream. The FileOutputStream class in Java supports files. It's a part of the java.io package. Bytes are used to store the data. When we need to write data into a newly generated file, we use the FileOutputStream class. A constructor to create a file is also provided by the FileOutputStream class. It is used for files that are already existing. 

The constructor's signature is:

public FileOutputStream(String name, boolean append) throws FileNotFoundException

where name is the file name, and 

append: If true, the byte will be written to the end of the file, not in the beginning.

Example

import java.io.FileOutputStream;
import java.util.Scanner;
public class fc_example2
{
    public static void main(String args[])
    {
        try
        {
            Scanner sc = new Scanner(System.in); 
            System.out.print("Enter the file name: ");
            String file = sc.nextLine(); 
            FileOutputStream fos=new FileOutputStream(file, true); //true for append mode
            System.out.print("Enter file content: ");
            String str = sc.nextLine()+"\n"; //str stores the string which we have entered
            byte[] b = str.getBytes(); //converts string into bytes
            fos.write(b); //writes bytes into file
            fos.close(); 
            System.out.println("File is saved.");
        }  
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Output

Must Read Type Conversion in Java

Java File.createFile() method

The File.createFile() function is part of the java.nio.file package's File class. It includes file support. The nio package is designed to work with buffers. A new, empty file can also be created using the createFile() function. When utilising this strategy, we don't need to close the resources. This is a benefit.

public static Path createFile(Path, Attribute) throws IOException

where, Path is the path to the file, and

The Attribute is an optional list of file attributes.

The function returns the file.

The example below also creates a new, empty file. Paths.get() is a static method in the Paths class (java.nio.file.Paths) that we use to build a Path instance. Take note of the following:

Path path = Paths.get("C:\\Users\\panis\\samplefile.txt");

In the above line, Paths is a class, and Path is an interface. Both are part of the same product. The Path Instance is created using the Paths.get() function.

Example

import java.io.IOException;
import java.nio.file.*;
public class fc_example3
{
    public static void main(String[] args)
    {
        Path path = Paths.get("C:\\Users\\panis\\samplefile.txt"); //creation of Path instance
        try
        {
            Path p= Files.createFile(path); //creates file at the specified location
            System.out.println("File Created at Path: " + p);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output

Practice it on online java compiler for better understanding.

Must Read Static Blocks In Java, Why is Java Platform Independent

FAQs

  1. What are exceptions in Java?
    An exception is an unwelcome or unexpected occurrence that occurs during the execution of a programme, i.e. at run time, and disturbs the program's usual flow of instructions. The application can detect and handle exceptions. When a method throws an exception, it creates an object. The exception object is the term given to this object. It contains details about the exception, such as the name and description of the error and the program's state when the error occurred.
     
  2. What is Exception handling?
    Exception Handling in Java is one of the most effective ways to manage runtime failures while maintaining the application's normal flow. ClassNotFoundException, IOException, SQLException, RemoteException, and other runtime errors are handled by Java Exception Handling.
     
  3. Explain try-catch in Java.
    The try block in Java is used to contain code that could potentially throw an exception. It has to be utilised as a part of the technique. The rest of the block code will not execute if an exception occurs at a specific statement in the try block. As a result, code that does not throw an exception should not be kept in a try block. A catch or a finally block must be used after a try block in Java.

    The Java catch block is utilised to handle the exception by declaring the kind of exception within the parameter. The parent class exception (i.e., exception) or the generated exception type must be defined. However, stating the type of exception generated is advisable. Only after the try block should the catch block be utilised. With a single try block, you can use many catch blocks. 
     
  4. What are packages?
    In Java, a package is a container for a collection of classes, sub-packages, and interfaces. Packages are used for the following purposes:

    → Packages are used for keeping name problems at bay. 
    → They make it easier to search for, locate, and use classes, interfaces, enumerations, and annotations.
    → They provide controlled access: package-level access control is available in both protected and default modes. Classes in the same package and its subclasses can access a protected member. Only classes in the same package have access to a default member (with no access specifier).
    → Packages are a type of data encapsulation (or data-hiding).

Key Takeaways

In this article, we learned how to create a file in Java. We saw three ways to create a file, namely, using File.createNewFile() method, using FileOutputStream class and using File.createFile() method. 

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on File Input/Output - Coding Ninjas Coding Ninjas Studio and File Input Stream class - Coding Ninjas Coding Ninjas Studio. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences, and much more!

Happy Reading!

Previous article
File Class in Java
Next article
File Handling in Java
Live masterclass