如您所知,我们在 java 中有多种工具可以将数据写入流。
在此示例代码中,我按运行时对它们进行了比较。
有人可以准确地解释一下吗?谢谢。
这是代码:
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IOtests
{
public static void main(String[] args) throws Exception
{
char[] chars = new char[100];
byte[] bytes = new byte[100];
for (int i = 0; i < 100; i++)
{
chars[i] = (char) i;
bytes[i] = (byte) i;
}
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(
"output.txt"));
long a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out.write(j);
System.out.println("OutputStreamWriter writing characters: "
+ (System.currentTimeMillis() - a));
out = new OutputStreamWriter(new FileOutputStream("output.txt"));
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out.write(j);
System.out.println("OutputStreamWriter writing bytes: "
+ (System.currentTimeMillis() - a));
PrintStream out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out1.write(j);
System.out.println("PrintStream writing characters: "
+ (System.currentTimeMillis() - a));
out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out1.write(j);
System.out.println("PrintStream writing bytes: "
+ (System.currentTimeMillis() - a));
PrintWriter out2 = new PrintWriter("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (char j : chars)
out2.write(j);
System.out.println("PrintWriter writing characters: "
+ (System.currentTimeMillis() - a));
out1 = new PrintStream("output.txt");
a = System.currentTimeMillis();
for (int i = 0; i < 100000; i++)
for (byte j : bytes)
out2.write(j);
System.out.println("PrintWriter writing bytes: "
+ (System.currentTimeMillis() - a));
}
}
结果:
OutputStreamWriter 写入字符:4141
OutputStreamWriter 写入字节:3546
PrintStream 写入字符:86516
PrintStream 写入字节:70484
PrintWriter 写入字符:938
PrintWriter 写入字节:2484
请注意,所有时间都以毫秒为单位。