3-16 自由编程

3-16 自由编程

public class StreamTest {
	public static void main(String[] args) {
		/**
		 * 将100000个字符分别写入one.txt和two.txt
		 * one不加缓冲的文件输出流来写,two用缓冲文件输出流来写
		 * 比较用时
		 */
		FileOutputStream fos;
		BufferedOutputStream bos;
		long InitialTime = 0;//起始时间
		long EndTime = 0;//结束时间
		long Buffered = 0;// 用缓冲所有时间
		long NoBuffered = 0; //没用缓冲所用时间
		try {
			//不用缓冲流来写
			fos = new FileOutputStream("one.txt");
			InitialTime = System.currentTimeMillis();
			for(int i=1;i<=100000;i++) {
				fos.write('a');
			}
			EndTime = System.currentTimeMillis();
			NoBuffered = EndTime-InitialTime;
			System.out.println("one.txt不使用缓冲流来写用时为:" + NoBuffered + "ms");
			
			//用缓冲流来写
			fos = new FileOutputStream("two.txt");
			bos = new BufferedOutputStream(fos);
			InitialTime = System.currentTimeMillis();
			for(int i=1;i<=100000;i++) {
				bos.write('a');
			}
			EndTime = System.currentTimeMillis();
			Buffered = EndTime-InitialTime;
			System.out.println("two.txt用缓冲流来写用时为:" + Buffered + "ms");
			System.out.println("节省时间:" + ( NoBuffered - Buffered) );
			
			//关闭资源
			bos.flush();
			bos.close();
			fos.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
结果:
one.txt不使用缓冲流来写用时为:207ms
two.txt用缓冲流来写用时为:2ms
节省时间:205
老师帮忙看一下,有没有哪里需要改进的地方


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学的代码完成的不错,有一点小小的建议:建议将流的关闭写在finally块中,这样即使发生异常,流也可以正常关闭。

祝:学习愉快~

  • jia_蛙 提问者 #1
    谢谢老师!
    2019-09-12 11:24:33
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星

相似问题

登录后可查看更多问答,登录/注册

请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师