Java IO流 -> 文件字节流和文件字符流封装FileUtil
import java.io.*;
public class FileUtil {
private InputStream in;
private OutputStream out;
private Reader read;
private Writer write;
private int size = 1024;
public FileUtil(){
}
public FileUtil(FileReader read, FileWriter write){
super();
this.read = read;
this.write = write;
}
public FileUtil(InputStream in, OutputStream out) {
super();
this.in = in;
this.out = out;
}
public void copyTxt(String srcFile, String destFile){
try{
this.read = new FileReader(srcFile);
this.write = new FileWriter(destFile);
this.copyTxt();
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyTxt(){
if(read == null || write == null){
throw new RuntimeException("输入输出流不可以为空!");
}
try{
char[] buf = new char[size];
for(int len = -1; (len = read.read(buf)) != -1; len++){
write.write(buf,0,len);
}
write.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
this.close(write,read);
}
}
public void copy(String srcFile, String destFile){
try{
this.in = new FileInputStream(srcFile);
this.out = new FileOutputStream(destFile);
this.copy();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
public void copy(){
if(in == null || out == null){
throw new RuntimeException("输入输出流不可以为空!");
}
try{
byte[] buf = new byte[size];
for(int len = -1; (len = in.read(buf)) != -1; len++){
out.write(buf,0,len);
}
out.flush();
}catch(IOException e){
e.printStackTrace();
}finally {
this.close(out,in);
}
}
private void close(Closeable ... args){
for(Closeable closeable : args){
try{
if(closeable != null){
closeable.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}