Java 的串流(Stream)是基礎中的基礎,檔案讀寫與拷貝更是面試常見考點。本文用同一個需求、三種實作做對照,順便量一下差異。
先記住一組對照:字元層級用 Reader/Writer(搭配 BufferedReader/BufferedWriter 提升效能),位元組層級用 InputStream/OutputStream(搭配 BufferedInputStream/BufferedOutputStream)。拷貝任意檔案時應走位元組流,才能避免編碼問題。
package com.gdufe.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestInputOutputStream {
private final static String SOURCE = "D:\\Tool_Software\\mysql-installer-community-5.6.23.0.msi";
private final static String TARGET = "mysql-installer-community-5.6.23.0.msi";
public static void main(String[] args) {
TestInputOutputStream.copy1(SOURCE, TARGET);
System.out.println("--End---");
}
public static void copy1(String src, String tar) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(src);
output = new FileOutputStream(tar);
int r;
while ((r = input.read()) != -1) {
output.write((byte) r);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
每次只搬一個位元組,功能正確但速度最差——每個位元組都是一次系統呼叫。
public static void copy2(String src, String tar) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(src);
output = new FileOutputStream(tar);
int length = 0;
byte[] b = new byte[1024];
while ((length = input.read(b)) != -1) {
output.write(b, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
一次搬 1KB,速度立刻改善一個量級。注意 write 的第三個參數必須是 length 而不是 b.length,否則最後一筆不足 1KB 時會寫入多餘的垃圾位元組。
public static void copy3(String src, String tar) {
InputStream input = null;
OutputStream output = null;
try {
input = new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tar)));
int length = 0;
byte[] b = new byte[1024]; // 先將資料讀入位元組陣列
while ((length = input.read(b)) != -1) {
output.write(b, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close(); // 關閉最外層即可,內層會一併關閉
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
實測加了 buffer 的版本確實更快,因為它大幅降低了實際的系統呼叫次數。
Files.copy(Paths.get(src), Paths.get(tar), StandardCopyOption.REPLACE_EXISTING);
另外,若來源與目標相同,自拷貝會出錯誤;需要「邊讀邊寫」時也應改用 FileChannel 的 transferTo,避免自己覆蓋自己。