Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Create / Write Files

Create a File

In Java, file creation is accomplished using the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that this method is enclosed within a try…catch block, as it throws an IOException if an error occurs (such as if the file cannot be created for some reason).

Example

import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors
public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The output expected is:

File created: filename.txt

To create a file within a particular directory (which requires permission), specify the file’s path. Use double backslashes to escape the “\” character on Windows. On Mac and Linux systems, you can directly specify the path, such as: /Users/name/filename.txt.

Example

File myObj = new File(“C:\\Users\\MyName\\filename.txt”);

Write To a File

In the subsequent example, we utilize the FileWriter class along with its write() method to write text to the file created in the previous example. It’s essential to remember that once writing to the file is complete, you should close it using the close() method.

Example

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors
public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The expected output is:

Successfully wrote to the file .