- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class BufferReaderAndWriter {
- public static void main(String[] args) {
- BufferedReader bufr = null;
- BufferedWriter bufw = null;
- File source = new File("D:\\a.txt");//创建要读取的文件(一般存在)
-
- File target = new File("D:\\b.txt");
- if(!target.exists()){
- try {
- target.createNewFile();//如果要写入的文件不存在,创建
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- try {
- //创建输入和输出流
- bufr = new BufferedReader(new FileReader(source));
- bufw = new BufferedWriter(new FileWriter(target));
- //格式化显示文件
- String str = null;
- while((str=bufr.readLine())!=null){
- bufw.write(str);//写入b.txt文件中
- //换行
- bufw.newLine();
- }
- //刷新缓冲区
- bufw.flush();
-
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- //关闭流资源
- if(bufr!=null){
- try {
- bufr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(bufw!=null){
- try {
- bufw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
复制代码 |
|