- 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.
- package com.instanceofjava.writetofile;
- import java.io.FileNotFoundException;
- import java.io.PrintWriter;
- /**
- *
- * @author www.instanceofjava.com
- * @category: java example program
- *
- * Description: Write a java example program to write string to files using PrintWriter
- *
- */
- public class WriteStringToFile {
- public static void main(String[] args) {
- String str="Write String to file";
- try( PrintWriter out = new PrintWriter("data.txt") )
- {
- out.println( str );
- }
- catch (FileNotFoundException e)
- {
- e.printStackTrace()
- }
- }
- }
No comments