Save text string to a file with BufferedWriter and FileWriter - Java File Path IO

Java examples for File Path IO:Text File

Description

Save text string to a file with BufferedWriter and FileWriter

Demo Code


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class Main {
       //w ww .  ja  v a2  s  . c o  m
        public static void main(String[] args) throws IOException {
                StringBuffer sbf = new StringBuffer();
               
                sbf.append("StringBuffer contents first line.");
                //new line
                sbf.append(System.getProperty("line.separator"));
                //second line
                sbf.append("StringBuffer contents second line.");
               
                BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("d:/demo.txt")));
               
                //write contents of StringBuffer to a file
                bwr.write(sbf.toString());
               
                bwr.flush();
               
                bwr.close();
               
                System.out.println("Content of StringBuffer written to File.");
        }
}
 

Related Tutorials