使用字符流拷贝文件:
import com.qf.ran.utils.IOUtils;
import org.junit.Test;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Demo01{
@Test
public void method(){
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("IOCopy1");//需要拷贝的文件
fw = new FileWriter("IOCopy1.1");//自动生成拷贝文件
char[] chars = new char[1024];
int len;
while((len = fr.read(chars))!= -1){
fw.writer(chars,0,len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
IOUtils.closeAll(fr,fw);//调用IOUtils方法关闭IO流
}
}
}
使用字节流拷贝文件:
import com.qf.ran.utils.IOUtils;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo03 {
@Test
public void method01(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("IO2.txt");
fos = new FileOutputStream("IO2.1.txt");
byte[] b = new byte[1024];
int len;
while((len = fis.read(b)) != -1){
fos.write(b,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
IOUtils.closeAll(fis,fos);
}
}
}
创建IO流Utils关闭方法:
import java.io.Closeable;
import java.io.IOException;
public class IOUtils {
public static void closeAll(Closeable ... closeables){
for (Closeable closeable:closeables) {
if(closeable != null){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}



