How to create new file in java

1. Overview

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

2. Create 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 new file is created and false if file already exists. This method also throws java.io.IOException when it’s not able to create the file. The files created is empty and of zero bytes.
  4. Observe the directory whether file is created or not.
package com.javaguides.javaio.fileoperations.fileexamples;

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());
  }
 }
}

3. Reference

Comments