Java program to write content into file using BufferedWriter

This program will write the content (string data) into the file using BufferedWriter class. We will create a file named "file2.txt" in the same directory.

BufferWriter takes the FileWriter type argument and FileWriter class defines that file. So we have to create mainly three object:

  • A File object to define the filename.
  • A FileWriter object to define the File using File Object.
  • A BufferedWriter objcet with respect of FileWriter object.

BufferedWriter.write() - This method is used to write String data into the file.

BufferedWriter.close() - This method is used to save and close the file.

Program will read content from the file line by line until null is not found.

Write Content into File using BufferedWriter in Java

// Java program to write content into file 
// using BufferedWriter

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;

public class ExBufferedWriter {
  public static void main(String args[]) {
    final String fileName = "file2.txt";

    try {
      File objFile = new File(fileName);
      if (objFile.exists() == false) {
        if (objFile.createNewFile()) {
          System.out.println("File created successfully.");
        } else {
          System.out.println("File creation failed!!!");
          System.exit(0);
        }
      }

      //writting data into file
      String text;
      Scanner SC = new Scanner(System.in);

      System.out.println("Enter text to write into file: ");
      text = SC.nextLine();

      //instance of FileWriter 
      FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
      //instnace (object) of BufferedReader with respect of FileWriter
      BufferedWriter objBW = new BufferedWriter(objFileWriter);
      //write into file
      objBW.write(text);
      objBW.close();

      System.out.println("File saved.");
    } catch (Exception Ex) {
      System.out.println("Exception : " + Ex.toString());
    }
  }
}

Output:

    
File created successfully.
Enter text to write into file: 
Computer is an Electronic Device.
File saved.

Java File Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.