Java : How to write a File in Java using FileWriter

Write a File in Java using FileWriter

You can write a file using FileWriter as shown in the code below.

package com.ekiras.demo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

class FileDemo {

 public static void main(String args[]) {
  readFile();
 }

 public static void readFile() {
  System.out.println(" Start :: writing file");
  try {
   File file = new File("/home/ekansh/myFile.txt");
   FileWriter fileWriter = new FileWriter(file);
   fileWriter.write("hello, this file is created at :: " + new Date());
   fileWriter.flush();
   fileWriter.close();
   System.out.println(" End :: writing file");
  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

You can write the data using the write() method and then call the flush() method to force the os to write to the file, finally close() method to close the file writer object, so that it can be garbage collected.

No comments :

Post a Comment