Search This Blog

Showing posts with label Managing Files and Directories in Java 7. Show all posts
Showing posts with label Managing Files and Directories in Java 7. Show all posts

Friday, 5 September 2014

Writing to File in Java - File Handling in Java

How to Write to File in Java - File Handling in Java

Formatter is used to write to file.

FileIO.java

import java.io.FileNotFoundException;
import java.util.Formatter;

public class FileIO {

 public static void main(String[] args) {
  String fileName = "myFile.txt";
  Formatter formatter = null;
  try {
   formatter = new Formatter(fileName);
  } catch (FileNotFoundException e) {
   System.err.println("Error opening or creating a file");
   e.printStackTrace();
  }
  formatter.format("Content to be written to %s", fileName);
  if (formatter != null)
   formatter.close();
  System.out.println("File written!");
 }

}