Create New File in Java

In this tutorial, we will learn how to create a new file in Java.

The java.io.File class can be used to create a new file in Java. When we initialize the File object, we provide the file name, and then we can call createNewFile() method to create a new file in Java.
 
File createNewFile() method returns true if a new file is created and false if the file already exists. This method also throws java.io.IOException when it’s not able to create the file. 

Create a New File Example

  1. Create File class object by passing file absolute location path "C://workspace/sample.txt"
  2. call createNewFile() method of file object to create new file named "sample.txt" file in directory "C://workspace"
  3. File createNewFile() method returns true if a new file is created and false if the file already exists. This method also throws java.io.IOException when it’s not able to create the file. 
  4. Observe the directory whether the file is created or not.
import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to create new file in Java.
 * @author javaguides.net
 */

public class CreateFileExample {
    private static final Logger LOGGER = LoggerFactory
        .getLogger(CreateFileExample.class);

    public static void main(String[] args) {
        createFile();
    }

    public static void createFile() {
        File file = new File("C:/workspace/sample.txt");
        try {
            if (file.createNewFile()) {
                LOGGER.info("File is created !!");
            } else {
                LOGGER.info("File is already exist");
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }
}

Create File using FileOutputStream

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;

public class WriteFile {

    /**
     * This class shows how to write file in java
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) {
        String data = "I will write this String to File in Java";
        int noOfLines = 10000;
        
        // Use Streams when you are dealing with raw data
        try(OutputStream os = new FileOutputStream(new File("C:/workspace/sample.txt"))){
            os.write(data.getBytes(), 0, data.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments