java第四次作業

來源:互聯網
上載者:User

標籤:

此程式最佳化讀取大的檔案(測試檔案為14M),寫成兩個靜態方法,方便調用,代碼如下:

 

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class Test {    public static void testFile(File filein, File fileout) throws IOException {        // 判斷檔案是否存在        if (!filein.exists()) {            System.out.println(filein.getName() + " 不存在 ");            throw new IOException();        }        // 如果檔案不存在,建立        if (!fileout.exists()) {            fileout.createNewFile();            throw new IOException();        }        FileInputStream in = new FileInputStream(filein);        FileOutputStream out = new FileOutputStream(fileout);        int b;        // copy        while ((b = in.read()) != -1) {            out.write(b);        }        in.close();        out.close();    }        public static void testFileQuick1(File filein, File fileout) throws IOException {        // 判斷檔案是否存在        if (!filein.exists()) {            System.out.println(filein.getName() + " 不存在 ");            throw new IOException();        }        // 如果檔案不存在,建立        if (!fileout.exists()) {            fileout.createNewFile();            throw new IOException();        }        FileInputStream in = new FileInputStream(filein);        FileOutputStream out = new FileOutputStream(fileout);        byte[] buf = new byte[20 * 1024];        int bytes = 0;        // copy        while ((bytes = in.read(buf, 0, buf.length)) != -1) {            out.write(buf, 0, bytes);        }        in.close();        out.close();    }    public static void main(String[] args) {        try {            long start = System.currentTimeMillis();            Test.testFile(new File("C:\\Users\\cumin\\Desktop\\1.mp3"),                    new File("C:\\Users\\cumin\\Desktop\\6.mp3 "));            long end = System.currentTimeMillis();            System.out.println(end - start);        } catch (IOException e) {            e.printStackTrace();        }    }}

通過靜態方法testFile按位元組讀取後複製需要:

Test.testFileQuick1(new File("C:\\Users\\cumin\\Desktop\\1.mp3"),                    new File("C:\\Users\\cumin\\Desktop\\6.mp3 "));            long end = System.currentTimeMillis();            System.out.println(end - start);

換成靜態方法testFileQuick1後 :

 

PS:讀取主要通過 read(byte[] b, int off, int len) 提升速度。

  寫主要通過 write(byte[] b, int off, int len) 提升速度。

複製速度大幅提升~~ 而且檔案不存在會自動建立。

java第四次作業

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.