• 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. }

save string to file

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu