Java Tutorial/Development/Formatter
Содержание
Formatter.ioException()
import java.io.FileOutputStream;
import java.util.Formatter;
public class Main {
public static void main(String[] argv) throws Exception {
Formatter fmtCon = new Formatter(System.out);
Formatter fmtFile;
fmtFile = new Formatter(new FileOutputStream("test.fmt"));
fmtCon.format("a negative number: %(.2f\n\n", -123.34);
fmtCon.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtCon.format("%8d %8d\n", i, i * i);
// write to the file.
fmtFile.format("This is a negative number: %(.2f\n\n", -123.34);
fmtFile.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtFile.format("%8d %8d\n", i, i * i);
fmtFile.close();
if (fmtFile.ioException() != null) {
System.out.println("File I/O Error Occurred");
}
}
}
locale-specific formatting.
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt = new Formatter();
fmt.format("Default locale: %tc\n", cal);
fmt.format(Locale.GERMAN, "For Locale.GERMAN: %tc\n", cal);
fmt.format(Locale.ITALY, "For Locale.ITALY: %tc\n", cal);
fmt.format(Locale.FRANCE, "For Locale.FRANCE: %tc\n", cal);
System.out.println(fmt);
}
}
new Formatter(new OutputStream("test.fmt"))
import java.io.FileOutputStream;
import java.util.Formatter;
public class Main {
public static void main(String[] argv) throws Exception {
Formatter fmtCon = new Formatter(System.out);
Formatter fmtFile;
fmtFile = new Formatter(new FileOutputStream("test.fmt"));
fmtCon.format("a negative number: %(.2f\n\n", -123.34);
fmtCon.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtCon.format("%8d %8d\n", i, i * i);
// write to the file.
fmtFile.format("This is a negative number: %(.2f\n\n", -123.34);
fmtFile.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtFile.format("%8d %8d\n", i, i * i);
fmtFile.close();
if (fmtFile.ioException() != null) {
System.out.println("File I/O Error Occurred");
}
}
}
Write formatted output directly to the console and to a file.
import java.io.FileOutputStream;
import java.util.Formatter;
public class Main {
public static void main(String[] argv) throws Exception {
Formatter fmtCon = new Formatter(System.out);
Formatter fmtFile;
fmtFile = new Formatter(new FileOutputStream("test.fmt"));
fmtCon.format("a negative number: %(.2f\n\n", -123.34);
fmtCon.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtCon.format("%8d %8d\n", i, i * i);
// write to the file.
fmtFile.format("This is a negative number: %(.2f\n\n", -123.34);
fmtFile.format("%8s %8s\n", "Value", "Square");
for (int i = 1; i < 20; i++)
fmtFile.format("%8d %8d\n", i, i * i);
fmtFile.close();
if (fmtFile.ioException() != null) {
System.out.println("File I/O Error Occurred");
}
}
}