老师看下有哪里需要优化吗?应该怎么正常输入整型

老师看下有哪里需要优化吗?应该怎么正常输入整型

try {
			
			FileOutputStream fos=new FileOutputStream("one.txt");
			FileOutputStream fos1=new FileOutputStream("two.txt");
			BufferedOutputStream bos=new BufferedOutputStream(fos1);
			//不用缓冲流
			System.out.println("one.txt不使用缓冲流来写");
			long startTime=System.currentTimeMillis();
			for(int i=0;i<100000;i++)
			{
				fos.write(i);
			}
			long endTime=System.currentTimeMillis();
			System.out.println("用时为:"+(endTime-startTime));
			//用缓冲流
			System.out.println("two.txt使用缓冲流来写");
			long playTime=System.currentTimeMillis();
			for(int i=0;i<100000;i++)
			{
				bos.write(i);
			}
			long overTime=System.currentTimeMillis();
			System.out.println("用时为:"+(overTime-playTime));
			System.out.println("节省时间:"+((endTime-startTime)-(overTime-playTime))+"ms");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}

应该怎么正常输入整型?

正在回答

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

2回答

同学的代码完成的不错,不过有一个小建议,建议使用完输入输出流后,使用close()方法将其关闭。

另外fos.write(i);已经向文件写入整型。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

  • 小老哥丶 提问者 #1
    我的意思是,正常的输入进去,而不会自动转换为ASCII码 比如i是1那就以1写入到文件里
    2019-11-12 10:59:27
  • 小老哥丶 提问者 #2
    另外为啥要先关闭缓冲流,才能关闭输出流? FileOutputStream是叫输出流吗?
    2019-11-12 11:03:14
好帮手慕阿满 2019-11-12 14:22:12

同学你好,FileOutputStream是输出流。创建缓存流时,是将输出流作为参数传入的,如:

http://img1.sycdn.imooc.com//climg/5dca4c1b0929b4a504820086.jpg

如果先关闭输出流,再使用缓冲流,就会报流关闭异常。所以需要先关闭缓冲流,再关闭输出流。

这里write()写入的会自动转换为ASCII码,我们只需要保证使用流读取出来的是正常的即可。或者同学可以存入字符1,如:

http://img1.sycdn.imooc.com//climg/5dca4f8f092e00d602280038.jpg

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

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

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

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

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