BufferedReader
和BufferedWriter
分别使用内部缓冲区来存储数据,同时进行读写。BufferedReader
提供了一个新方法readLine()
,它读取一行并返回一个String(不带行分隔符)。
以下示例显示了BufferedReader
和BufferedWriter
的使用。
文件:BufferedReaderWriterExample.java –
package com.yiibai.tutorial.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author yiibai
*/
public class BufferedReaderWriterExample {
public static void main(String[] args) {
File file = new File("file.txt");
/*Writing file using BufferedWriter*/
FileWriter fileWriter = null;
BufferedWriter bufferedWriter =null;
try {
fileWriter=new FileWriter(file);
bufferedWriter =new BufferedWriter(fileWriter);
bufferedWriter.write("This is an example /n");
bufferedWriter.write("of using BufferedWriter and /n");
bufferedWriter.write("BufferedReader.");
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileWriter!=null){
fileWriter.close();
}
if(bufferedWriter!=null){
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/*Reading file using BufferedReader*/
FileReader fileReader=null;
BufferedReader bufferedReader=null;
try {
fileReader =new FileReader(file);
bufferedReader=new BufferedReader(fileReader);
String line=null;
while((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileReader!=null){
fileReader.close();
}
if(bufferedReader!=null){
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
执行上面示例代码,得到以下结果(文件:file.txt):
This is an example
of using BufferedWriter and
BufferedReader.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/276197.html