10.文件字符缓冲流
作者:互联网
1.文件字符缓冲流-字符缓冲输入流
这里使用的 BufferedReade 字符缓冲输入流来提高读写效率,对于字符来说,是通过一行一行读取的 readLine()
import java.io.BufferedReader;
import java.io.FileReader;
public class Dome07 {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader("d:/a.txt");//创建文件字符输入流对象
br = new BufferedReader(fr);//创建文件字符缓冲输入流对象
String temp = "";
while ((temp = br.readLine())!=null){
System.out.println(temp);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (br!=null){
br.close();
}
if (fr!=null){
fr.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
2.文件字符缓冲流-字符缓冲输出流
import java.io.BufferedWriter;
import java.io.FileWriter;
public class Dome08 {
public static void main(String[] args) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter("d:/c.txt");//创建文件字符输出流对象
bw = new BufferedWriter(fw);//创建文件字符缓冲输出流对象
bw.write("123");
bw.newLine();//换行
bw.write("456");
bw.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (bw!=null){
bw.close();
}
if (fw!=null){
fw.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
3.基于字符缓冲流的文本文件拷贝工具类
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Dome09 {
public static void main(String[] args) {
copyText("d:/a.txt","d:/b.txt");
}
public static void copyText(String src,String des){
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(src));
bw = new BufferedWriter(new FileWriter(des));
String temp = "";
while ((temp = br.readLine())!=null){
bw.write(temp);
bw.newLine();//换行处理,由于这里是读一行,写一行,所有进行换行一下比较好
}
bw.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (br!=null){
br.close();
}
if (bw!=null){
bw.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
标签:10,java,io,字符,缓冲,bw,br,null 来源: https://www.cnblogs.com/lyq888/p/16131451.html