1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.justexample.java.io; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class PrintWriterExample { public static void main(String[] args) { String filename = "c:" + File.separator + "JustExample.txt"; File f = new File(filename); PrintWriter pw = null; try { pw = new PrintWriter(f); String strContent = "Just Example"; int intContent = 1; double doubleContent = Math.random(); //convinient way to add new line while print content pw.println(strContent); //using printf to format content. SInce java 1.5 pw.printf("Hello this is %s. I am %d years old. My lucky number is %f", strContent, intContent, doubleContent); pw.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ //no matter what happen. close the output stream always. //note that closing a printer will not throw IOException if(pw!=null){ pw.close(); } } } } |
Reference
http://docs.oracle.com/javase/1.5.0/docs/api/java/io/PrintWriter.html
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html