Java Program to Create File and Write to the File

Java Program to Create File and Write to the File

What are File System?

In Java, a file system is a set of classes and interfaces that provide a standard way for reading and writing files and directories. The most commonly used file system classes are those in the java.io package, such as File, FileInputStream, and FileOutputStream.

In this Article, we will write a program to Count number of lines present in the file.

File System in Java :

In Java, the file system can be accessed and manipulated through the java.io and java.io packages.

The java.io package provides classes such as File, FileInputStream, and FileOutputStream for working with files and directories. The File class can be used to create, delete, and manipulate files and directories. The FileInputStream and FileOutputStream classes can be used to read and write data to files, respectively.
The java.io package, which was introduced in Java 1.4, provides advanced file system functionality such as file channel I/O and memory-mapped file I/O. The java.nio package includes classes such as Path, FileChannel, and MappedByteBuffer that can be used to perform low-level file system operations such as reading, writing, and manipulating file metadata.

Additionally, the java.io.file package, which was introduced in Java 7, provides a more modern and versatile file system API. The java.nio.file package includes classes such as the Path, Files, and FileSystem classes, which can be used to perform various file system operations, including reading, writing, and manipulating file metadata.

Program to Create a File :

Run
// importing the File class
import java.io.File;

class Main {
  public static void main(String[] args) {
    // create a file object for the current location
    File file = new File("example.java");
    try {
      // creating a new file
      if (file.createNewFile()) {
        
        // if the file is created  
        System.out.println("File is created.");
      }else {
          
        // if the file is already exists  
        System.out.println("The file already exists.");
      }
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

Explanation:

This program creates a new file named “example.java” in the current working directory. The File class is used to represent a file or directory path and the createNewFile() method is used to create a new, empty file. If the file already exists, the program will print “The File already exists.” to the console. If an error occurs, and the stack trace of the error using e.getStackTrace().
It’s worth noting that the file is created in the same directory as the program and if you want to create the file in a specific directory you have to provide the directory path.

Program to Write Content to the File :

Run
import java.io.*;

public class WriteFile {
  public static void main(String[] args) {
    try {
        
      // Creating a new file
      FileWriter writer = new FileWriter("example.txt", true);
      
      // Writing a message in the file
      writer.write("This is a new line of text.");
      
      // Closing a file
      writer.close();
      System.out.println("Successfully wrote to the file.");
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Explanation:

This program writes the string “This is a new line of text.” to the file “example.txt” in the current working directory. The FileWriter class is used to write text to a file. The FileWriter constructor takes the file name as the first argument and a boolean value as the second argument. The boolean value determines whether to append to the file or overwrite it. In this case, it’s set to true to append the text to the file.

The write() method is used to write the string to the file. Then the close() method is used to close the file and release the resources. If an error occurs, the program will print “An error occurred” and the stack trace of the error using e.printStackTrace().
It’s worth noting that if the file doesn’t exist the program will throw an exception.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription