FileInputStream,FileOutputStream,FileReader,FileWriter这些都是计算机与硬盘之间发生的io操作,基于硬盘的读写相对是比较慢的,这个操作的速度受到硬盘的读写速度的制约,为了能够提高读写速度,于是产生了缓冲流。
缓冲流基于内存,先把数据缓冲到内存中,再内存去做io操作,基于内存的io操作,比基于硬盘的io操作快75000多倍。
缓冲字节输入流BufferedInputStream:
public static void testBufferedInputStream(){
// 文件字节输入流对象
FileInputStream in = new FileInputStream(".....");
//把文件字节输入流放到缓冲字节输入流对象
BufferedInputStream br = new BufferedInputStream(in);
byte[] b = new byte[10];
int len = 0;
while((len = br.read(b)) != -1){
System.out.println(new String(b,0,len));
}
//关闭流时,最晚开的最早关
br.close();
in.close();
}
缓冲字节输出流BufferedOutputStream:
public static void testBufferedOutputStream(){
FileOutputStram out = new FileOutputStream("...");
BufferedOutputStream bo = new BufferedOutputStream(out);
String s = "...";
bo.write(s.getBytes());//转换成btye数组,写道内存中
bo.flush();//刷到硬盘上
bo.close();
out.close();
}
缓冲流实现文件的复制:
public static void copyFile(){
//缓冲输入流
FileInputStream in = new FileInputStream(".....");
BufferedInputStream br = new BufferedInputStream(in);
//缓冲输出流
FileOutputStram out = new FileOutputStream("...");
BufferedOutputStream bo = new BufferedOutputStream(out);
byte[] b = new byte[1024];
int len = 0;
while((len = br.read()) != -1){
bo.write(b,0,len);//写到内存中
}
bo.flush();//刷到硬盘
bo.close();
out.close();
br.close();
in.close();
}
缓冲字符流BufferedReader:
public static void testBufferedReader(){
FileReader r = new FileReader("...");
BufferedReader br = new BufferedReader(r);
char[] c = new char[100];
while((len = br.read(c)) != -1){
System.out.println(new String(c,0,len));
}
br.close();
r.close();
}
br.read( c )读到文件最后一个字符的下一位,返回值是-1。
缓冲字符输出流BufferedWriter:
public static void testBufferedWriter(){
FileWriter fw = new FileWriter("...");
BufferedWriter bw = new BufferedWriter(fw);
String s = "...";
bw.write(s);
bw.flush();
bw.close();
fw.close();
}
缓冲字符流实现文件的复制:
public static void copyFile(){
FileReader r = new FileReader("...");
BufferedReader br = new BufferedReader(r);
FileWriter fw = new FileWriter("...");
BufferedWriter bw = new BufferedWriter(fw);
char[] c = new char[1024];
while((len = br.read(c)) != -1){
bw.write(c,0,len);
}
bw.flush();
bw.close();
fw.close();
br.close();
r.close();
}
所有的文件都有编码格式,对于我们来说,TXT和Java文件一般来讲有三种编码:
ISO8859-1,西欧编码,是纯粹的英文编码,不适应汉字;
GBK和UTF-8,这两种编码是适用于中文和英文。
我们一般使用UTF-8。
转换流提供了在字节流和字符流之间的转换。
转换输入流为字符输入流InputStreamReader:
public static void testInputStreamReader(){
FileInputStream fs = new FileInputStream("...");
InputStreamReader in = new InputStreamReader(fs,"GBK");
char[] c = new char[100];
int len = 0;
while((len = in.read(c)) != -1){
System.out.println(new String(c,0,len));
}
in.close();
fs.close();
}
转换输出流为字符输出流OutputStreamWriter:
public static void testOutputStreamWriter(){
FileOutputStream out = new FileOutputStream("...");
OutputStreamWriter os = new OutputStreamWriter(out,"GBK");
os.write("...");
os.flush();
os.close();
out.close();
}