唯一注意的一点
字符缓冲流的输出流有新方法,不能多态。
字节缓冲流
public class 字节缓冲流输入流 {
//选择源
public static void main(String[] args) {
File file = new File("king.txt");
//选择流
InputStream in= null;
try {
in = new BufferedInputStream(new FileInputStream(file));//在此处做了包装
//操作(分段读取)
byte [] flush =new byte [128];//缓冲容器
int len = -1;//接收容器
while((len = in.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!=in) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class 字节缓冲流输出流 {
public static void main(String[] args) {
//选择源
File file =new File("king.txt");
//选择流
OutputStream output =null;
try {
output = new BufferedOutputStream(new FileOutputStream(file ,true));
//操作
String s ="我又来了";
byte [] n=s.getBytes();//编码
output.write(n, 0, n.length);
output.flush();//刷新
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//关闭流
if(null!=output) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
字符缓冲流 之文本的copy
public class 字符缓冲流之文本的copy {
public static void main(String[] args) {
copy("文件字符流测试.txt","t.txt");
}
public static void copy(String srcpath,String destpath) {
//选择源
//File file1 =new File("1.jpg");
//File file2 =new File("copy.jpg");
File file1 =new File(srcpath);
File file2 =new File(destpath);
//选择流
try(BufferedReader in =new BufferedReader(new FileReader(file1));//加缓冲流
BufferedWriter out = new BufferedWriter(new FileWriter(file2))){//try() 释放资源
//操作
String line =null;
while((line =in.readLine())!=null) {
out.write(line);//逐行写出
out.newLine();//换行
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}