老师帮忙查看一下代码,有啥地方是需要优化的,谢谢老师

来源:3-16 自由编程

迷惘一缕

2020-08-02 20:36:25

package com.imooc.file;


import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;


public class BufferedDemo {


public static void main(String[] args) throws IOException {

//实现FileOutputStream对象

File one=new File("e://java//File","one.txt");

File two=new File("e://java//File","two.txt");

long start=0,end=0;

if(!one.exists()) {

try {

one.createNewFile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(!two.exists()) {

try {

two.createNewFile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//文件输出流

FileOutputStream fos=null;

try {

fos=new FileOutputStream("e://java//File//one.txt",true);

long startTime1=System.currentTimeMillis();

int n=0,a=65;

while(n<100000) {

fos.write((char)a);

a+=1;

n++;

if(a>122) {

a=65;

}

}

long endTime1=System.currentTimeMillis();

start=endTime1-startTime1;

System.out.println("one.txt不使用缓冲流来写");

System.out.println("用时为:"+start);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch(IOException e) {

e.printStackTrace();

} finally {

fos.close();

}

//缓冲输出流

FileOutputStream fos1=null;

BufferedOutputStream bos=null;

try {

fos1=new FileOutputStream("e://java//File//two.txt",true);

bos=new BufferedOutputStream(fos1);

long startTime2=System.currentTimeMillis();

int n=0,a=65;

while(n<100000) {

bos.write((char)a);

a+=1;

n++;

if(a>122) {

a=65;

}

}

bos.flush();

long endTime2=System.currentTimeMillis();

end=endTime2-startTime2;

System.out.println("two.txt使用缓冲流来写");

System.out.println("用时为:"+end);

System.out.println("节省时间为:"+(start-end));

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e){

e.printStackTrace();

} finally {

fos1.close();

bos.close();

}

}


}


写回答

1回答

好帮手慕小脸

2020-08-03

同学你好,代码没有问题,完成的很棒!继续加油~

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

0

0 学习 · 16556 问题

查看课程