通过缓冲区复制文本文件

时间:2022-03-28 16:44:02
/*通过缓冲区复制文本文件 通过缓冲区复制一个.java文件。 */
import java.io.*;
class CopyTextByBuf {
    public static void main(String[] args) 
    {       
        BufferedReader bufr = null;//读取
        BufferedWriter bufw = null;//写入

        try
        {
            bufr = new BufferedReader(new FileReader("BufferedWriterDemo.java"));//读取
            bufw = new BufferedWriter(new FileWriter("bufWriter_copy.txt"));//写入

            String line = null;
            while ((line= bufr.readline())!=null)//判断非空,读取行
            {
                bufw.write(line);//循环写入行
                bufw.newLine();//换行
                bufw.flush();//刷新
            }
        }
        catch (IOException e)
        {
            throw new RuntimeException("读写失败");
        }
        finally
        {
            try
            {
                if(bufr!=null)//判断非空
                    bufr.close();
            }
            catch (IOException e)
            {
                throw new RuntimeException("读取关闭失败");
            }

            try
            {
                if(bufw!=null)//判断非空
                    bufw.close();
            }
            catch (IOException e)
            {
                throw new RuntimeException("写入关闭失败");
            }
        }
    }
}