import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 第八题:使用带缓冲功能的字节流复制文件
*/
public class Test8{
public static void main(String args[]){
//创建BufferedInputStream对象
BufferedInputStream bufins = null;
//创建BufferedOutputStream对象
BufferedOutputStream bufouts = null;
try {
//创建BufferedInputStream对象
bufins = new BufferedInputStream(new FileInputStream("c:\\test.txt"));
//创建BufferedOutputStream对象
bufouts = new BufferedOutputStream(new FileOutputStream("c:\\testcopy.txt"));
int byteRead = 0;
//按字节读取内容,结尾处read会返回-1
while ((byteRead = bufins.read()) != -1) {
bufouts.write(byteRead);
}
} catch (IOException e) {
//读取过程捕获到异常抛出”复制失败“提示
throw new RuntimeException("复制失败");
} finally {
try {
//关闭 BufferedInputStream
if (bufins != null) bufins.close();
} catch (IOException e) {
//关闭BufferedInputStream过程捕获到异常抛出失败提示
throw new RuntimeException("读取关闭失败");
}
try {
//关闭BufferedOutputStream
if (bufouts != null) bufouts.close();
} catch (IOException e) {
//关闭BufferedOutputStream过程捕获到异常抛出失败提示
throw new RuntimeException("写入关闭失败");
}
}
}
}
|
|