Java Write Files

 

Java FileWriter class of java.io package is used to write data in character form to file. Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java.

Create a File

To create a file in Java, you can use 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 the method is enclosed in a try-catch block. This is necessary because it throws an IOException if an error occurs.

  • Get the current working directory (user. dir)
  •  Create a file using Java code
  • Declare an object>instantiate the object>call create file method

Example:

public class fileCreate{
  public static void main (String[] args){

     // Get the current working directory (user.dir)
      String currentDir = System.getProperty("user.dir");

     // Create a file with path using Java code
     String filePath = currentDir + "/createNewFiles.txt";

  try {
      File createFile=new File(filePath);
      if(createFile.createNewFile())
         System.out.println("File created "+createFile.getName());	
       else
         System.out.println("File already exist");
   }
  catch(IOException e){
    System.out.println("Error")    
   }
  }//main
}//class

 

Output:

File created createNewFiles.txt

There are multiple ways to write a text file in Java. this is required while dealing with many applications. There are several ways to write a plain text file in Java, e.g., you can use FileWriter or BufferedWriter to write a text file.

File write using FileWriter:

  1. FileWriter is the simplest way to write a file in Java. It provides an overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.

Example:

//write file using fileWriter
import java.io.FileWriter;
import java.io.IOException;
public class fileWriter{
   public static void main (String[] args){
     try {
        FileWriter myWriter = new FileWriter("createNewFilesss.txt");
        myWriter.write("File create & wrote Successfully ");
        myWriter.close();
     } 
     catch (IOException e) {
         System.out.println("An error occurred.");
          e.printStackTrace();
     }
  }//main
}//class

Output:

In TextFile: File create & wrote Successfully

File write using BufferedWriter:

BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.

Example 1:

public class fileWriter{
   public static void main (String[] args){

        // Content to be assigned to a file
         String text = "Computer Science Portal DumbSchools";

        // Try block to check if exception occurs
       try {
              // Get the current working directory (user.dir)
              String currentDir = System.getProperty("user.dir");

             // File path of the file to read
              String filePath = currentDir + "/fileWriter.txt";
 
             // Create a FileWriter object
             // to write in the file
            FileWriter fWriter = new FileWriter( filePath);              
 
            // Writing into file
            // Note: The content taken above inside the
            // string
            fWriter.write(text);
 
            // Printing the contents of a file
            System.out.println(text);
 
            // Closing the file writing connection
            fWriter.close();
 
            // Display message for successful execution of
            // program on the console
            System.out.println("File is created successfully with the content.");  
        } 
            // Catch block to handle if exception occurs
      catch (IOException e) { 
            // Print the exception
             System.out.print(e.getMessage());
      }
  }//main
}//class

Output:

In TextFile:Computer Science Portal DumbSchool

Console: File is created successfully

Example 2:

public class filWriter{
  public static void main (String[] args){

    // Content to be assigned to a file

    String text = "Computer Science Portal DumbSchool";
   
   // Try block to check if exception occurs
  try {	 
      // Create a FileWriter object
      // to write in the file
      FileWriter fWriter = new FileWriter( "C:\\Java\\workspace\\file_IO/fileWriter.txt");
         
      // Writing into file
      // Note: The content taken above inside the
      // string
            fWriter.write(text);
 
            // Printing the contents of a file
            System.out.println(text);
 
            // Closing the file writing connection
            fWriter.close();

            // Display message for successful execution of
           // program on the console
            System.out.println( "File is created successfully ");     
    } 
  // Catch block to handle if exception occurs
     catch (IOException e) {
            // Print the exception
       System.out.print(e.getMessage());
     }
  }//main
}//class

Output:

In TextFile: Computer Science Portal DumbSchool

Console: File is created successfully

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close