Java FileWriter Example

FileWriter creates a Writer that you can use to write to a file. FileWriter is a convenience class for writing character files. 

FileWriter class Example

FileWriter is meant for writing streams of characters so provide input for the below program is character string like:
String content = "This is the text content";
This program writes character streams to file "sample.txt" file. This example uses the try-with-resources statement to close the resources automatically.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * The class demonstrate the usage of FileWriter class methods.
 * @author javaguides.net
 *
 */

public class FileWritterExample {
 public static void main(String[] args) {
  File file = new File("sample.txt");
  String content = "This is the text content";

  try (FileWriter fop = new FileWriter(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
   fop.write(content);

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Reference

Comments