Q:

Java program to write content into file using BufferedWriter

belongs to collection: Java File Handling Programs

0

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:

  • File object to define the filename.
  • FileWriter object to define the File using File Object.
  • 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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to read content from file using Buffe... >>
<< Java program to read content from file using FileI...