字节字符输入输出流
** 以下内容均可以直接运行 **
简介
缓冲流和打印流都是为了 提高输入输出流的效率 而出现的
缓冲流
原本的输入输出流是通过while一个一个字节或者一个一个字符打印文本的,这样做会让计算机和文件频繁的发生数据连接,这样做得效率很低下,所以出现了 缓冲流 把要输出的文字先存放在缓存中,当缓存满时一起写入(缓存默认的大小为8KB)
打印流
原本的要用多行语句打印,现在只要用ps.println()方法即可实现,提高效率
缓冲流(内含注释)
import java.io.*;
/*
* 缓冲流
* 用于将需要输入输出的文件先存放在缓存中,达到一定数量时一起输入输出,减少文件的读写操作提高效率
* try方法可以自动关闭流*/
public class BufferStreamDemo {
public static void main(String[] args) {
BufferByteOut();
BufferByteIn();
BufferCharOut();
BufferCharIn();
}
//输出缓冲流 默认缓冲为8KB,即8KB刷新一次,也可以在构造函数中自己重新定义缓存大小
// 另外在java 1.8后,无需关闭输出流,只要关闭缓冲流就可以了。
public static void BufferByteOut(){
File f = new File("c:\\test\\BufferOut.txt");
try {
//1.分开写 2.合并写
// OutputStream out = new FileOutputStream(f);
// BufferedOutputStream bos = new BufferedOutputStream(out);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
String s = "这是一个字节缓冲流实验";
bos.write(s.getBytes());
bos.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
//输出缓冲流 默认缓冲为8KB,即8KB刷新一次,也可以在构造函数中自己重新定义缓存大小
public static void BufferByteIn() {
File f = new File("c:\\test\\BufferOut.txt");
try {
//1.分开写 2.合并写
// InputStream in = new FileInputStream(f);
// BufferedInputStream bis = new BufferedInputStream(in);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
byte[] b = new byte[1024];
int lens = -1;
while ((lens = bis.read(b))!=-1){
System.out.println(new String(b,0,lens));
}
bis.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public static void BufferCharOut() {
File f = new File("c:\\test\\BufferCharOut.txt");
try(BufferedWriter bw = new BufferedWriter(new FileWriter(f))){
String s = "这是一个字符缓冲流实验";
bw.write(s);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public static void BufferCharIn() {
File f = new File("c:\\test\\BufferCharOut.txt");
try(BufferedReader br = new BufferedReader(new FileReader(f))){
int lens = -1;
char[] ch = new char[1024];
while((lens = br.read(ch))!=-1){
System.out.println(new String(ch,0,lens));
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
整合后的打印流和缓冲流
import java.io.*;
public class PrintStreamDemo {
public static void main(String[] args) {
bytePrint();
charPrint();
}
private static void bytePrint() {
File f = new File("c://test//bytePrint.txt");
try (PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(f)))) {
ps.println("这是一个字节打印流实验");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void charPrint() {
File f = new File("c://test//charPrint.txt");
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f)))) {
pw.println("这是一个字节打印流实验");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}