Java/File Input Output/Print To Files
illustrates using a PrintWriter to handle console output
import java.io.PrintWriter;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Printing an HTML Table
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
public class HTMLDemo {
public static void main(String[] a) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter("test.html"));
DecimalFormat ff = new DecimalFormat("#0"), cf = new DecimalFormat(
"0.0");
pw.println("<TABLE BORDER><TR><TH>Fahrenheit<TH>Celsius</TR>");
for (double f = 100; f <= 400; f += 10) {
double c = 5 * (f - 32) / 9;
pw.println("<TR ALIGN=RIGHT><TD>" + ff.format(f) + "<TD>"
+ cf.format(c));
}
pw.println("</TABLE>");
pw.close(); // Without this, the output file may be empty
}
}
Printing Numbers to a Text File
import java.io.FileWriter;
import java.io.PrintWriter;
public class PrintWriterDemo {
public static void main() throws Exception{
PrintWriter pw = new PrintWriter(new FileWriter("dice.txt"));
for (int i = 1; i <= 1000; i++) {
int die = (int) (1 + 6 * Math.random());
pw.print(die);
pw.print(" ");
if (i % 20 == 0)
pw.println();
}
pw.println();
pw.close(); // Without this, the output file may be empty
}
}