以前IO流復(fù)制文件
private static void test01() throws IOException {
// 字符流復(fù)制文本文件
FileReader fis = new FileReader("JDK10\\files\\a.txt");
FileWriter fos = new FileWriter("JDK10\\files\\b.txt");
char[] chs = new char[1024 * 8];
int len;
while ((len = fis.read(chs)) != -1) {
fos.write(chs, 0, len);
}
fis.close();
fos.close();
}
以上代碼要自己定義數(shù)組,編寫循環(huán)讀取和寫數(shù)據(jù)的代碼,比較麻煩。使用JDK10的 transferTo 方法就很簡單 了。
JDK10使用transferTo方法復(fù)制文件
JDK10 給 InputStream 和 Reader 類中新增了 transferTo 方法, transferTo 方法的作用是將輸入流讀取的數(shù)據(jù) 使用字符輸出流寫出??捎糜趶?fù)制文件等操作。
private static void test02() throws IOException {
FileReader fis = new FileReader("JDK10\\files\\a.txt");
FileWriter fos = new FileWriter("JDK10\\files\\c.txt");
fis.transferTo(fos);
fis.close();
fos.close();
}
我們只需要調(diào)用 transferTo 方法就可以復(fù)制文件了。我們來看看 Reader 類的 transferTo 源碼:
public long transferTo(Writer out) throws IOException {
Objects.requireNonNull(out, "out");
long transferred = 0;
char[] buffer = new char[TRANSFER_BUFFER_SIZE];
int nRead;
while ((nRead = read(buffer, 0, TRANSFER_BUFFER_SIZE)) >= 0) {
out.write(buffer, 0, nRead);
transferred += nRead;
}
return transferred;
}
小結(jié)
JDK10中給輸入流InputStream&Reader新增了transferTo,可以將輸入流中的數(shù)據(jù)轉(zhuǎn)到輸出流中.方便文件的復(fù)制