Java Write Files

 

To write data in character form to a file, utilize the Java FileWriter class found in the java.io package. Character-oriented data can be written to a file using the Java FileWriter class. 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. If the file was successfully created, this method returns true, if the file already exists, it returns false. Take note that a try-catch block encloses the method. This is required because in the event of an error, it throws an IOException.

  • 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. The simplest method for writing a file in Java is FileWriter. To write an int, byte array, or string to a file, it offers an overloaded write method. With FileWriter, you may also write a portion of a String or byte array. FileWriter should only be used when there are fewer writes because it writes straight into files.

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:

Although it uses an internal buffer to write data into files, BufferedWriter and FileWriter are nearly identical. Therefore, performance is improved and actual IO operations are reduced when there are more write operations. 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