#节点流和处理流实例
BufferedReader和BufferedWriter的使用
BufferedReader:
package com.reader_;
import java.io.BufferedReader;
import java.io.FileReader;
//演示BufferedReader 使用
public class BufferedReader_ {
public static void main(String[] args) throws Exception{
String filePath = "E:\\JavaStudy\\code\\JavaSe\\BasicGramma\\src\\com\\oop\\demo01\\Student.java";
//创建BufferedReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
//读取
String line;//按行读取
//readLine()是按行读取文件,当返回null时,表示读取完毕
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
//关闭流,这里只需要关闭BufferedReader这个包装流即可,因为底层会自动关闭节点流
bufferedReader.close();
}
}
BufferedWriter:
package com.reader_;
import java.io.BufferedWriter;
import java.io.FileWriter;
//演示BufferedWriter 的使用
public class BufferedWriter_ {
public static void main(String[] args) throws Exception{
String filePath = "E:\\JavaStudy\\a.txt";
//创建BufferedWriter
//new FileWriter(filePath,true)是以追加的方式写入
//new FileWriter(filePath)是以覆盖的方式写入
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));//传入true后是以追加的方式写入
bufferedWriter.write("hello1,学好数理化");
bufferedWriter.newLine();//插入一个和系统相关的换行符
bufferedWriter.write("hello2,走遍天下都不怕");
bufferedWriter.newLine();//插入一个和系统相关的换行符
bufferedWriter.write("hello3,考的都会");
bufferedWriter.newLine();//插入一个和系统相关的换行符
bufferedWriter.write("hello4,蒙的都对");
//关闭外层流即可,传入的new FileWriter(filePath) 会在底层自动关闭
bufferedWriter.close();
}
}
BufferedCopy:
package com.reader_;
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
//说明:
//1. BufferedReader和BufferedWriter是安装字符操作
//2. 不要去操作二进制文件【声音,视频,doc,PDF,等等】,否则可能会造成文件损坏
//原文件
String srcFilePath = "E:\\JavaStudy\\a.txt";
//目标
String destFilePath = "E:\\JavaStudy\\note\\a.txt";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
try {
br = new BufferedReader(new FileReader(srcFilePath));
bw = new BufferedWriter(new FileWriter(destFilePath));
//说明:readLine()读取一行内容,但是没有换行
while ((line = br.readLine()) != null){
bw.write(line);
//插入一个换行
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null){
br.close();
}
if (bw != null){
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("copy完毕");
}
}