前言:
Java中流是重要的內容,基礎的文件讀寫與拷貝知識點是很多面試的考點。故通過本文進行簡單測試總結。
2.圖展示【文本IO/二進制IO】(這是參考自網上的一張總結圖,相當經典,方便對比記憶)
3.文本復制的實驗Java實現code:
package com.gdufe.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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="t.txt";
// private final static String TARGET="tt.txt";
// private final static String SOURCE="p.png";
// private final static String TARGET="pp.png";
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";
//D:\Tool_Software\Ryuyan.zip
public static void main(String[] args) {
// TestInputOutputStream.copy1(SOURCE, TARGET);
// TestInputOutputStream.copy2(SOURCE, TARGET);
TestInputOutputStream.copy3(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();
}
}
}
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)));
/***經過親測,buffer緩沖流讀取時確實更快一些****/
int length=0;
byte []b = new byte[1024]; //先將stream讀入字節數組
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();
}
}
}
}
(附:參考代碼時注意准備好測試文件,不然出現異常“file can't be found”!
文件拷貝到Java工程的直接目錄下,刷新project可查看!)
以上內容純屬個人學習總結,不代表任何團體或單位。若有理解不到之處請見諒!