BufferedReader 和 BufferedWriter
实现类中具有新方法,即声明并创建对象时不要使用多态,否则无法使用类中的新方法。
BufferedReader新方法:String readLine(),即读一行文字。
BufferedWriter新方法:void newLine(),即写一个换行符。
BufferedReader测试代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 测试BufferedReader
* @author dxt
*
*/
public class TestBufferedReader {
public static void main(String[] args){
//1.创建源
File src = new File("F:/myjava/IO_Study03/abc.txt");
//2. 选择流
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(src)); //缓冲流的底层都需要节点流
//进行读取操作
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
//释放资源
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally{
try{
if(null != br){
br.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
}
BufferedWriter测试代码
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 测试BufferedWriter
* @author dxt
*
*/
public class TestBufferedWriter {
public static void main(String[] args){
//创建源
File dest = new File("F:/myjava/IO_Study03/abc.txt");
//选择流
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(dest, true));
//输出操作
String datas = "铁马冰河入梦来";
bw.newLine();
bw.write(datas);
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
if(null != bw){
bw.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
}
纯文本拷贝实现
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 利用BufferedReader 和 BufferedWriter 对文件进行copy()
* 仅能对纯文本进行拷贝
* @author dxt
*
*/
public class TestBufferedCopy {
public static void main(String[] args){
String src = "F:/myjava/IO_Study03/abc.txt";
String dest = "F:/myjava/IO_Study03/abc_copy.txt";
copy(src, dest);
}
/**
* 将源文件src中的内容拷贝到dest中
* @param source
* @param destination
*/
public static void copy(String source, String destination){
//创建源
File src = new File(source);
File dest = new File(destination);
//选择流
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(src));
bw = new BufferedWriter(new FileWriter(dest, true));
//进行读取写入操作
String flush = null;
while((flush = br.readLine()) != null){ //读一行写一行
bw.write(flush);
bw.newLine();
}
//资源释放
bw.flush();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
try{
if(null != bw){
bw.close();
}
} catch(IOException e){
e.printStackTrace();
}
try{
if(null != br){
br.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
}