字符缓冲流
1、基本用法
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileReader; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 /** 8 * BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。 9 * BufferedWriter:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 10 * @author Administrator 11 * 12 */ 13 public class BufferedStreamDemo { 14 public static void main(String[] args) throws IOException { 15 //创建缓冲流对象 16 BufferedWriter bw=new BufferedWriter(new FileWriter("C:\\Test\\bw.txt")); 17 bw.write("hello"); 18 //bw.flush(); 19 bw.close(); 20 21 //一次读取一个字符 22 //创建输入缓冲流对象 23 BufferedReader br=new BufferedReader(new FileReader("C:\\Test\\bw.txt")); 24 int ch; 25 while((ch=br.read())!=-1) { 26 System.out.print((char)ch); 27 } 28 br.close(); 29 System.out.println(); 30 //一次读取一个字符数组 31 BufferedReader br2=new BufferedReader(new FileReader("C:\\Test\\bw.txt")); 32 int len=0; 33 char chs[]=new char[1024]; 34 while((len=br2.read(chs))!=-1) { 35 System.out.print(new String(chs,0,len)); 36 } 37 br2.close(); 38 } 39 }
2、缓冲流复制文本文件两种方式
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileReader; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 /** 8 * 需求:把项目路径下的BufferedStreamCopy.java中的内容复制到项目路径下的copy.java中 9 * @author Administrator 10 * 11 */ 12 public class BufferedStreamCopy { 13 public static void main(String[] args) throws IOException { 14 BufferedReader br=new BufferedReader(new FileReader("BufferedStreamCopy.java")); 15 BufferedWriter bw=new BufferedWriter(new FileWriter("copy.java")); 16 //第一种方式,一次读取一个字符 17 // int ch; 18 // while((ch=br.read())!=-1) { 19 // bw.write(ch); 20 // } 21 22 //第二种方式,一次读取一个字符数组 23 int len; 24 char[] chs=new char[1024]; 25 while((len=br.read(chs))!=-1) { 26 bw.write(chs,0,len); 27 } 28 29 br.close(); 30 bw.close(); 31 32 } 33 }
3、缓冲流的特殊功能
BufferedWriter:
void newLine():写一个换行符,这个换行符由系统决定
BufferedReader
String readLine():一次读取一行数据,但是不读取换行符
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileReader; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 7 /** 8 * 需求:把项目路径下的BufferedStreamCopy.java中的内容复制到项目路径下的copy.java中 9 * @author Administrator 10 * 11 */ 12 public class BufferedStreamCopy { 13 public static void main(String[] args) throws IOException { 14 BufferedReader br=new BufferedReader(new FileReader("copy1.java")); 15 BufferedWriter bw=new BufferedWriter(new FileWriter("copy2.java")); 16 String str; 17 while((str=br.readLine())!=null) { 18 bw.write(str); 19 bw.newLine(); 20 } 21 br.close(); 22 bw.close(); 23 24 BufferedReader brshow=new BufferedReader(new FileReader("copy2.java")); 25 String str2; 26 while((str2=brshow.readLine())!=null) { 27 System.out.println(str2); 28 } 29 brshow.close(); 30 31 } 32 }
原文地址:https://www.cnblogs.com/hopeyes/p/9710533.html
时间: 2024-10-08 02:12:05