FileOutputStream,BufferedOutputStream,FileWriter 效率比較

   測試代碼:測試

/**
     * 寫文件   
     * FileOutputStream, BufferedOutputStream, FileWriter
     * 三個流   效率比較
     */
    @Test
    public void writeFile() throws Exception {
        FileOutputStream out = null;
        
        FileOutputStream outSTr = null;
        BufferedOutputStream Buff = null;
        
        FileWriter fw = null;

        int count = 999;//寫文件行數

        try {
            //FileOutputStream
            out = new FileOutputStream(new File("F:/FileOutputStream.txt"));
            long begin = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                out.write("輸出流測試文件 \r\n".getBytes());
            }
            out.close();
            long end = System.currentTimeMillis();
            System.out.println("FileOutputStream執行耗時:" + (end - begin) + " 毫秒");

            //BufferedOutputStream
            outSTr = new FileOutputStream(new File("F:/BufferedOutputStream.txt"));
            Buff = new BufferedOutputStream(outSTr);
            long begin0 = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                Buff.write("輸出流測試文件\r\n".getBytes());
            }
            Buff.flush();
            Buff.close();
            long end0 = System.currentTimeMillis();
            System.out.println("BufferedOutputStream執行耗時:" + (end0 - begin0) + " 毫秒");

            //FileWriter
            fw = new FileWriter("F:/FileWriter.txt");
            long begin3 = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                fw.write("輸出流測試文件\r\n");
            }
            fw.close();
            long end3 = System.currentTimeMillis();
            System.out.println("FileWriter執行耗時:" + (end3 - begin3) + " 毫秒");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
                Buff.close();
                outSTr.close();
                out.close();
            } catch (Exception e) {
                throw new Exception("流關閉異常!");
            }
        }

    }

  運行結果:spa

      

相關文章
相關標籤/搜索