標籤:
此程式最佳化讀取大的檔案(測試檔案為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第四次作業