您的位置:首页 > 编程语言 > Java开发

Java IO(二):IO流——处理流——缓冲流

2016-08-13 14:20 344 查看
IO流——处理流——缓冲流

1.节点流与处理流的关系:

节点流处于IO操作的第一线,所有操作必须通过他们进行。处理流可以对其他流进行处理(提高效率或操作灵活性),处理流在节点流之上。

2.缓冲流:

(1)字节缓冲流

BufferedInputStream

BufferedOutputStream

/**
* 字节流文件的拷贝+缓冲流
* @param srcPath
* @param destPath
* @throws IOException
*/
public static void copyFile(String srcPath, String destPath) throws IOException{
//1、建立联系  源(存在且为文件) + 目的地(文件可以不存在)
File src = new File(srcPath);
File dest = new File(destPath);

if (!src.isFile()) {
System.out.println("不是文件");
throw new IOException("只能拷贝文件");
}

//2、选择流
InputStream inputStream = new BufferedInputStream(new FileInputStream(src));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(dest));

//3、文件拷贝    循环+读取+写出
byte[] flush = new byte[1024];
int len = 0;
//读取
while (-1 != (len = inputStream.read(flush))) {
//写出
outputStream.write(flush,0,len);
}
outputStream.flush();   //强制刷出

//4、释放资源    关闭流
outputStream.close();
inputStream.close();
}


(2)字符缓冲流

BufferedReader             readLine()

BufferedWriter                newLine()

public static void main(String[] args) {
//1.创建源
File src = new File("D:/IOtest/demo.txt");
File dest = new File("D:/IOtest/char.txt");
//2.选择流
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(src));
writer = new BufferedWriter(new FileWriter(dest));
//读取操作
/*
char[] flush = new char[1024];
int len = 0;
while (-1 != (len=reader.read(flush))) {
writer.write(flush,0,len);
} */

 //新增方法,使用新增方法不能产生多态
String line = null;
while (null != (line=reader.readLine())) {
writer.write(line);
writer.newLine();   //换行
}
writer.flush();//强制刷出
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("源文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: