Saturday, March 12, 2016

Java I/O Examples : How To Write String Content Into The File

Intro


This examples, will demonstrates how to write a simple file using String contents. To write this file, you can use FileWriter class.

Examples


package com.freesamplecode.java.io;

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

public class WriteFileDemo {
 public static void main(String[] args) {
  String contents = "This is a content will be append in the file";

  File file = new File("D:/temp/testfile.txt");
  
  FileWriter fw = null;
  try {
   if (!file.exists()) {
    file.createNewFile();
   }
   
   fw = new FileWriter(file);
   fw.write(contents);
   
   fw.close();
   
   System.out.println("File "+file.getAbsolutePath() + " has been successfully created");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally{
   if(fw != null){
    try {
     fw.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}


Output


File D:\temp\testfile.txt has been successfully created

Screenshot


How To Write String Content Into The File Using Java Program

Related Posts:

0 comments: