Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java program to write a string to file using PrintWriter

Tags: string java write
  • We can write a string to text file in java in various ways.
  • Using PrintWriter we can write or append a string to the text file. 
  • Using println() method of PrintWriter we can save or write string to text file.
  • After completion of using PrintWriter you need to close it by calling close() method.
  • If you are using java 7 , by using try with resources we can implement it and closing will be taken care automatically.
  • Now we will see an example program on how to write or save a string / string variable  to a text file using java 7.

#1: Java Example program to write or save String to file using PrintWriter and java 7 try with resources.

  1. package com.instanceofjava.writetofile;
  2. import java.io.FileNotFoundException;
  3. import java.io.PrintWriter;
  4. /**
  5.  * 
  6.  * @author www.instanceofjava.com 
  7. * @category: java example program
  8.  * 
  9.  * Description: Write a java example program to write string to files using PrintWriter 
  10.  * 
  11. */
  12. public class WriteStringToFile {
  13.  
  14.  public static void main(String[] args) { 
  15.        String str="Write String to file";  
  16.  try(  PrintWriter out = new PrintWriter("data.txt")  )
  17.            
  18. out.println( str );    
  19. catch (FileNotFoundException e) 
  20. {  
  21. e.printStackTrace()
  22.      
  23. }
  24. }   
  25. }




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Java program to write a string to file using PrintWriter

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×