1. 程式人生 > 其它 >Java實驗9 T1.往檔案中寫入1萬個隨機數,比較用時的多少

Java實驗9 T1.往檔案中寫入1萬個隨機數,比較用時的多少

技術標籤:Java

題目要求

分別使用FileWriter 和 BufferedWriter 往檔案中寫入1萬個隨機數,比較用時的多少?(用時採用方法System.currentTimeMillis())求時間差;

FileWriter

import java.io.FileOutputStream;
import java.io.IOException;

public class Test1 {
	public static void main(String[] args) throws IOException {
		FileOutputStream output = new FileOutputStream
("temp.dat"); long start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { output.write((int) (Math.random()*10)); } long stop = System.currentTimeMillis(); long time = stop-start; System.out.println("時間差為:"+ time +"毫秒"); } }

BufferedWriter

import
java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test1 { public static void main(String[] args) throws IOException { BufferedOutputStream bouput = new BufferedOutputStream( new FileOutputStream("temp2.dat"
)); long start2 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { bouput.write((int) (Math.random()*10)); } long stop2 = System.currentTimeMillis(); long time2 = stop2-start2; System.out.println("BufferedWriter的時間差為:"+ time2 +" 毫秒"); } }

在這裡插入圖片描述