Java/File Input Output/Print To Files

Материал из Java эксперт
Перейти к: навигация, поиск

illustrates using a PrintWriter to handle console output

   <source lang="java">

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);
 }

}

</source>
   
  
 
  



Printing an HTML Table

   <source lang="java">

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("");
   for (double f = 100; f <= 400; f += 10) {
     double c = 5 * (f - 32) / 9;
pw.println("
FahrenheitCelsius
" + ff.format(f) + ""
         + cf.format(c));
   }
pw.println("
");
   pw.close(); // Without this, the output file may be empty
 }

}

      </source>
   
  
 
  



Printing Numbers to a Text File

   <source lang="java">

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
 }

}

      </source>