Problem : How you can write line by line data to a text file?
Solution : java.io.FileWriter creates/open an existing file and with help of its write()method you can write charcter by charcter to text file. java.io.PrintWriter takes a line and convert it into charters and pass charcters to java.io.FileWriter . Program :Step 1 - CodingCreate a text file c:/sunilos/WriteFile.java and copy below contents.import java.io.FileWriter; import java.io.PrintWriter; import java.io.Writer; /** * A program to write in a file. */ public class WriteFile { public static void main(String[] args) throws Exception{ //File writer takes chars and convert into bytes and write to a file FileWriter writer = new FileWriter("c:/sunilos/sunilos-write.txt"); // PrintWriter takes lines and convert that into charters and gives to FileWriter PrintWriter printWriter = new PrintWriter(writer); for(int i=0;i<5;i++){ printWriter.println(i +" : Line"); } printWriter.close(); writer.close(); System.out.println("DONE"); } } Step 2 - Deployment
Step 3 - Testing
OutputDONEFAQWhat is FileWriter?
What is PrintWriter?
<<Previous | Next>> |