缓冲区写入硬盘细节:首先你要知道缓冲区是有大小的,当你写入的字节(字符)达到缓冲区的上限时,才会写入硬盘!
那么我们的程序一般通过什么样的方式处理没有达到缓冲上限的字节(字符)呢?
答:通过两种方式:flush()和close(),都是间接让缓冲区强行写入硬盘。
如果在没有达到缓冲上限时,且没有close()和flush(),你会发现并没有写入硬盘中即生成相应的文件。
(一)文件拷贝+字节缓冲流2
package d_IOBuffered;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class BufferedByte {
public static void main(String[] args) {
String src="G:/iotest/IOBuffered/a.txt";
String dest="G:/iotest/IOBuffered/demo3";
try {
copyFile(src,dest);
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件不存在");
}
}
/**
* 文件的拷贝
*/
public static void copyFile(String srcPath,String destPath) throws IOException{
//1.建立联系: 源文件(存在且为文件) + 目的地(可以不存在)
File src=new File(srcPath);
File dest=new File(destPath);
if(!src.isFile()||!src.exists()){
/* System.out.println(" 只能拷贝文件");
return;*/
throw new IOException("只能拷贝文件");
}
//2.选择流
InputStream is=new BufferedInputStream(new FileInputStream(src));
OutputStream os=new BufferedOutputStream(new FileOutputStream(dest));
//3.操作:拷贝=循环+读取+写出
byte[] flush=new byte[1024];
int len=0;
while(-1!=(len=is.read(flush))){
os.write(flush,0,len);
}
os.flush();
//关闭流
os.close();
is.close();
}
}
说明:
1.处理流必须在节点流基础上嵌套
2)文件拷贝+字符缓冲流+新增方法
package d_IOBuffered;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/**
* 字符缓冲流+新增方法(readLine(),newLine())
* 特别注意:因为有新增方法,所以不能使用多肽。
*
* @author john
*
*/
public class BufferedChar {
public static void main(String[] args){
//创建源
File src=new File("G:/iotest/IOChar/b.txt");
File dest=new File("G:/iotest/IOBuffered/bb.txt");
//选择流
BufferedReader reader=null;
BufferedWriter wr=null;
try {
//读取操作
reader=new BufferedReader(new FileReader(src));
wr=new BufferedWriter(new FileWriter(dest));
String line=null;
while(null!=(line=reader.readLine())){
wr.write(line);//读取一行
wr.newLine();//等同于wr.append("\r\n"):换行
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭流
try {
reader.close();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
重点说明:
1)BufferedReader,BufferedWriter有新增方法,所以不能使用多肽。
Reader reader=new BufferedReader(new FileReader(src)) ;//-->错误
BufferedReader reader=new BufferedReader(new FileReader(src)) ;//-->正确
2)BufferedReader新增方法有:readLine()读取一行(不含换行符)。
BufferedWrite新增方法有:newLine()换行符,与append("\r\n")效果相同。
说明:自己可以查看api,比对其余Reader,Write基类的区别。