JavaSE 学习参考:字符流包装流

来源:互联网 发布:比亚乔台风150电喷数据 编辑:程序博客网 时间:2024/06/09 23:04
   

ReaderWriter代表字符输入流和字符输出流,它们读写是以字符为单位的,但在处理字符信息量比较多,性能较低。BufferedReaderBufferedWriter是对字符输入流和字符输出流包装,其内置缓冲区,允许一次读写一行,既提高了性能也带来了编程的方便,实际我们在字符IO处理时,使用这两个类场景比较多。常用方法列举如下:

BufferedReader: 

String readLine(); 从流中读取一行字符,以\n作为行标记

BufferedWriter:

writer(String);将字符串输出到目标流中。

newline();将换行符\n输出到目标字符流中。

 

示例1代码:

  public class TestBufferedWriter {

public static void main(String[] args) {

Writer writer = null;

BufferedWriter bw=null;

try {

writer = new FileWriter("rw.txt");

bw=new BufferedWriter(writer);

bw.write("字符包装流");

bw.newLine();

bw.write("字符包装流");

bw.newLine();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (bw != null) {

try {

bw.flush();

bw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (writer != null) {

try {

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

 

 

 

示例2代码:

public class TestReader {

public static void main(String[] args) {

Reader reader = null;

BufferedReader br=null;

try {

reader = new FileReader("rw.txt");

br=new BufferedReader(reader);

String line=null;

while((line=br.readLine())!=null){

System.out.println(line);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (br != null) {

try {

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

 

}

}

 

0 0
原创粉丝点击