格式化开销
实际上,将数据写入文件只是输出开销的一部分。另外一个巨大的开销是数据的格式 化。考虑下面的三个例 子,要求其输出如下的行:
The square of 5 is 25
方法 1
第一种方法是简单地输出一个固定串,以得到内部I/O开销的概念:
public class format1 {
public static void main(String args[]) {
final int COUNT = 25000;
for (int i = 1; i <= COUNT; i++) {
String s = "The square of 5 is 25\n";
System.out.print(s);
}
}
}
方法 2
第二种方法采用带"+"的简单格式化:
public class format2 {
public static void main(String args[]) {
int n = 5;
final int COUNT = 25000;
for (int i = 1; i <= COUNT; i++) {
String s = "The square of " + n + " is " + n * n + "\n";
System.out.print(s);
}
}
}
方法 3
第三种方法使用了java.text包中的类MessageFormat:
import java.text.*;
public class format3 {
public static void main(String args[]) {
MessageFormat fmt =
new MessageFormat("The square of {0} is {1}\n");
Object values[] = new Object[2];
int n = 5;
values[0] = new Integer(n);
values[1] = new Integer(n * n);
【问题提问、论坛交流】编辑:xker.com

发表评论