package chj.io1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 文件字节输入输出流 加入字节缓冲流
* 1、创建源
* 2、选择源
* 3、操作
* 4、释放资源
* @author Administrator
*
*/
public class BufferedTest01 {
public static void main(String[] args) {
bufferedTest01();
bufferedTest02();
}
public static void bufferedTest01(){
//创建源
File src=new File("abc.txt");
InputStream is=null;
try {
is=new BufferedInputStream(new FileInputStream(src));
byte[] flush=new byte[1024];//缓冲容器
int len=-1;//接收长度
while((len=is.read(flush))!=-1) {
//字节数组-->字符串(解码)
String str=new String(flush, 0, len);
System.out.println(str);
}
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//多个流释放的时候从底层开始释放,但其实可以只写最外层的释放,其他可自动释放
if(null!=is) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void bufferedTest02() {
File dest=new File("dest.txt");//文件不存在则可以创建
OutputStream os=null;
try {
os=new BufferedOutputStream(new FileOutputStream(dest,false));//为false则是覆盖写入,为true则是追加写入
String msg="chai hong jun tong xue zheng zai nu li xue xi java";
byte[] datas=msg.getBytes();
os.write(datas, 0, datas.length);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(null!=os) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
【JAVA】IO之字节缓冲流,用以加快IO效率
最新推荐文章于 2023-04-19 20:46:07 发布