Java IO流之【缓冲流和文件流复制文件对比】
生活随笔
收集整理的這篇文章主要介紹了
Java IO流之【缓冲流和文件流复制文件对比】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
與文件流相比,緩沖流復制文件更快
代碼:
package Homework;import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat;/*** 1 )將"今年是反法西斯勝利70周年,舉國歡慶,所以要放假啦" 字符串* 使用文件字符輸出流 寫入到oldhappy.dt文件中,復寫10000行,* 要求換行 在文件的開頭寫入當前的時間 精確到毫秒在文件的結尾也寫入當前的時間 精確到毫秒。* @author Administrator**/ public class Test1 {public static void main(String[] args) {copy1();copy2();}//使用文件流復制文件public static void copy1(){FileOutputStream fos=null;try {//創建輸入流,并創建要寫入的文件oldhappy.dtfos=new FileOutputStream(new File("oldhapy.dt"));//獲取寫入前的當前時間long l=System.currentTimeMillis();//格式化時間SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");String time=s.format(l);//寫入時間fos.write((time+"\r\n").getBytes());//寫入要寫的內容,并換行 // \r\n表示換行for(int i=1;i<=10000;i++){fos.write("今年是反法西斯勝利70周年,舉國歡慶,所以要放假啦\r\n".getBytes());fos.flush();}//獲取寫完后 時間long l2=System.currentTimeMillis();String time2=s.format(l2);fos.write(time2.getBytes());//復制文件的時間System.out.println("使用文件流復制文件時間:"+(l2-l));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {if(fos!=null){try {fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//使用緩沖流復制文件public static void copy2(){BufferedOutputStream bos=null;try {bos=new BufferedOutputStream(new FileOutputStream("newhapy.dt"));long l=System.currentTimeMillis();//格式化時間SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");String time=s.format(l);//寫入時間bos.write((time+"\r\n").getBytes());//寫入要寫的內容,并換行 // \r\n表示換行for(int i=1;i<=10000;i++){bos.write("今年是反法西斯勝利70周年,舉國歡慶,所以要放假啦\r\n".getBytes());bos.flush();}//獲取寫完后 時間long l2=System.currentTimeMillis();String time2=s.format(l2);bos.write(time2.getBytes());//復制文件的時間System.out.println("使用緩沖流復制文件時間:"+(l2-l));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {if(bos!=null){try {bos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}運行結果比較:
總結
以上是生活随笔為你收集整理的Java IO流之【缓冲流和文件流复制文件对比】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java IO流之缓冲流
- 下一篇: Java IO流之对象流