Java/Language Basics/Formatted IO

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

Demonstrate a field-width specifier.

   <source lang="java">

import java.util.*;

public class FormatDemo4 {

 public static void main(String args[]) { 
   Formatter fmt = new Formatter(); 

   fmt.format("|%f|%n|%12f|%n|%012f|", 10.12345, 10.12345, 10.12345); 

   System.out.println(fmt); 

 } 

}


      </source>
   
  
 
  



Demonstrate the format specifier.

   <source lang="java">

import java.util.*;

public class FormatDemo2 {

 public static void main(String args[]) { 
   Formatter fmt = new Formatter(); 

   for(double i=1000; i < 1.0e+10; i *= 100) { 
     fmt.format("%g ", i); 
     System.out.println(fmt); 
   } 

 } 

}

      </source>
   
  
 
  



Demonstrate the format specifiers 2.

   <source lang="java">

import java.util.*;

public class FormatDemo3 {

 public static void main(String args[]) { 
   Formatter fmt = new Formatter(); 

   fmt.format("Copying file%nTransfer is %d%% complete", 88); 
   System.out.println(fmt); 
 } 

}


      </source>
   
  
 
  



Formatted Input output: A very simple example that uses Formatter.

   <source lang="java">

import java.util.*;

public class FormatDemo {

 public static void main(String args[]) { 
   Formatter fmt = new Formatter(); 

   fmt.format("Formatting %s is easy %d %f", "with Java", 10, 98.6); 

   System.out.println(fmt); 
 } 

}


      </source>
   
  
 
  



Formatting time and date.

   <source lang="java">

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   // Display standard 12-hour time format.
   fmt.format("%tr", cal);
   System.out.println(fmt);
   // Display complete time and date information.
   fmt = new Formatter();
   fmt.format("%tc", cal);
   System.out.println(fmt);
   // Display just hour and minute.
   fmt = new Formatter();
   fmt.format("%tl:%tM", cal, cal);
   System.out.println(fmt);
   // Display month by name and number.
   fmt = new Formatter();
   fmt.format("%tB %tb %tm", cal, cal, cal);
   System.out.println(fmt);
 }

} /*02:18:02 PM Fri Jun 08 14:18:02 PDT 2007 2:18 June Jun 06

  • /
      </source>
   
  
 
  



Java formatted IO: Demonstrate printf().

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   System.out.println("Here are some numeric values " + "in different formats.\n");
   System.out.printf("Various integer formats: ");
   System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
   System.out.println();
   System.out.printf("Default floating-point format: %f\n", 1234567.123);
   System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
   System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
   System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);
   System.out.println();
   System.out.printf("Line-up positive and negative values:\n");
   System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
 }

}

/* Here are some numeric values in different formats. Various integer formats: 3 (3) +3 00003 Default floating-point format: 1234567.123000 Floating-point with commas: 1,234,567.123000 Negative floating-point default: -1,234,567.123000 Negative floating-point option: (1,234,567.123000) Line-up positive and negative values:

1,234,567.12

-1,234,567.12

  • /
      </source>
   
  
 
  



Java formatted IO: findInLine().

   <source lang="java">

import java.util.Scanner; public class MainClass {

 public static void main(String args[]) {
   String instr = "Name: Tom Age: 28 ID: 77";
   Scanner conin = new Scanner(instr);
   conin.findInLine("Age:");
   if (conin.hasNext())
     System.out.println(conin.next());
   else
     System.out.println("Error!");
 }

}


      </source>
   
  
 
  



Java formatted IO: the left justification.

   <source lang="java">

import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   // Right justify by default
   fmt.format("|%10.2f|", 123.123);
   System.out.println(fmt);
   // Now, left justify.
   fmt = new Formatter();
   fmt.format("|%-10.2f|", 123.123);
   System.out.println(fmt);
 }

}


| 123.12| |123.12 |

      </source>
   
  
 
  



Java formatted IO: the precision modifier.

   <source lang="java">

import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   // Format 4 decimal places.
   fmt.format("%.4f", 123.1234567);
   System.out.println(fmt);
   // Format to 2 decimal places in a 16 character field.
   fmt = new Formatter();
   fmt.format("%16.2e", 123.1234567);
   System.out.println(fmt);
   // Display at most 15 characters in a string.
   fmt = new Formatter();
   fmt.format("%.15s", "Formatting with Java is now easy.");
   System.out.println(fmt);
 }

}


      </source>
   
  
 
  



Java formatted IO: the space format specifiers.

   <source lang="java">

import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   fmt.format("% d", -100);
   System.out.println(fmt);
   fmt = new Formatter();
   fmt.format("% d", 100);
   System.out.println(fmt);
   fmt = new Formatter();
   fmt.format("% d", -200);
   System.out.println(fmt);
   fmt = new Formatter();
   fmt.format("% d", 200);
   System.out.println(fmt);
 }

}

/*

* 

-100

100

-200

200
  • /
      </source>
   
  
 
  



Java formatted IO: Use Scanner to compute an average of the values.

   <source lang="java">

import java.util.Scanner; public class MainClass {

 public static void main(String args[]) {
   Scanner conin = new Scanner(System.in);
   int count = 0;
   double sum = 0.0;
   System.out.println("Enter numbers to average.");
   while (conin.hasNext()) {
     if (conin.hasNextDouble()) {
       sum += conin.nextDouble();
       count++;
     } else {
       String str = conin.next();
       if (str.equals("done"))
         break;
       else {
         System.out.println("Data format error.");
         return;
       }
     }
   }
   System.out.println("Average is " + sum / count);
 }

}

      </source>
   
  
 
  



Java formatted IO: Use Scanner to compute an average of the values in a file.

   <source lang="java">

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class MainClass {

 public static void main(String args[]) throws IOException {
   int count = 0;
   double sum = 0.0;
   FileWriter fout = new FileWriter("test.txt");
   fout.write("2 3.4 5 6 7.4 9.1 10.5 done");
   fout.close();
   FileReader fin = new FileReader("Test.txt");
   Scanner src = new Scanner(fin);
   while (src.hasNext()) {
     if (src.hasNextDouble()) {
       sum += src.nextDouble();
       count++;
     } else {
       String str = src.next();
       if (str.equals("done"))
         break;
       else {
         System.out.println("File format error.");
         return;
       }
     }
   }
   fin.close();
   System.out.println("Average is " + sum / count);
 }

}


      </source>
   
  
 
  



Java Formatter: Create a table of squares and cubes.

   <source lang="java">

import java.util.*;

public class FieldWidthDemo {

 public static void main(String args[]) { 
   Formatter fmt; 
 
   for(int i=1; i <= 10; i++) { 
     fmt = new Formatter(); 

     fmt.format("%4d %4d %4d", i, i*i, i*i*i); 
     System.out.println(fmt); 
   } 

 } 

}


      </source>
   
  
 
  



Java new formatted IO : format tester

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class FormatTester {

 public static void main(String[] args) {
   String filename = "name";
   try {
     File file = new File(filename);
     FileReader fileReader = new FileReader(file);
     BufferedReader reader = new BufferedReader(fileReader);
  
     String line;
     int i = 1;
     while ((line = reader.readLine()) != null) {
       System.out.printf("Line %d: %s%n", i++, line);
     }
   } catch (Exception e) {
     System.err.printf("Unable to open file named "%s": %s", 
                       filename, e.getMessage());
   }
 }

}

      </source>
   
  
 
  



Use arguments indexes to simplify the creation of a custom time and date format.

   <source lang="java">

import java.util.Calendar; import java.util.Formatter; public class MainClass {

 public static void main(String args[]) {
   Formatter fmt = new Formatter();
   Calendar cal = Calendar.getInstance();
   fmt.format("Today is day %te of %<tB, %<tY", cal);
   System.out.println(fmt);
 }

}


//Today is day 8 of June, 2007


      </source>
   
  
 
  



Use Scanner to compute an average a list of comma-separated values.

   <source lang="java">

import java.util.*; import java.io.*;

public class SetDelimiters {

 public static void main(String args[]) 
   throws IOException { 

   int count = 0; 
   double sum = 0.0; 

   FileWriter fout = new FileWriter("test.txt"); 

   fout.write("2, 3.4,    5,6, 7.4, 9.1, 10.5, done"); 
   fout.close(); 

   FileReader fin = new FileReader("Test.txt"); 

   Scanner src = new Scanner(fin); 

   src.useDelimiter(", *"); 

   while(src.hasNext()) { 
     if(src.hasNextDouble()) { 
       sum += src.nextDouble(); 
       count++; 
     } 
     else { 
       String str = src.next();  
       if(str.equals("done")) break; 
       else { 
         System.out.println("File format error."); 
         return; 
       } 
     } 
   } 

   fin.close(); 
   System.out.println("Average is " + sum / count); 
 } 

}


      </source>
   
  
 
  



Use Scanner to read various types of data from a file.

   <source lang="java">

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class MainClass {

 public static void main(String args[]) throws IOException {
   int i;
   double d;
   boolean b;
   String str;
   FileWriter fout = new FileWriter("test.txt");
   fout.write("Testing Scanner 10 12.2 one true two false");
   fout.close();
   FileReader fin = new FileReader("Test.txt");
   Scanner src = new Scanner(fin);
   while (src.hasNext()) {
     if (src.hasNextInt()) {
       i = src.nextInt();
       System.out.println("int: " + i);
     } else if (src.hasNextDouble()) {
       d = src.nextDouble();
       System.out.println("double: " + d);
     } else if (src.hasNextBoolean()) {
       b = src.nextBoolean();
       System.out.println("boolean: " + b);
     } else {
       str = src.next();
       System.out.println("String: " + str);
     }
   }
   fin.close();
 }

}


      </source>