首页 > 其他分享 >IO4 - 字符流

IO4 - 字符流

时间:2023-01-04 15:13:22浏览次数:28  
标签:字符 writer IO4 File reader new null TODO

IO - 文件 - 字符流

BufferedReader\PrintWriter 每次传输一行数据

public class FileString {
    public static void main(String[] args) throws Exception{

        //TODO IO 文件复制

        //数据源文件对象
        File srcFile = new File("E:\\.就业\\code\\day1\\IO_File\\test.txt");

        //数据目的文件对象(自动生成)
        File destfile = new File("E:\\.就业\\code\\day1\\IO_File\\test.txt.copy");

        //TODO BufferedReader  字符输入流(管道对象)
        BufferedReader reader = null;
        //TODO PrintWriter  字符输出流(管道对象)
        PrintWriter writer = null;

        try{
            //TODO FileReader对象通过字符读取文件
            reader = new BufferedReader(new FileReader(srcFile));
            writer = new PrintWriter(destfile);

            //TODO StringBuilder 创建空字符串对象
            StringBuilder ss = new StringBuilder();

            //读取文件中一行数据(字符串)
            String line = null;

            while ((line = reader.readLine()) != null){
                System.out.println(line);
                writer.println(line);
            }

            //TODO .flush() 刷写数据
            writer.flush();
            //读取的一行数据进入缓存区,flush刷新缓冲区,即将缓冲区中的数据立刻写入文件,同时清空缓冲区



        }catch (IOException e){
            throw new RuntimeException(e);
        }finally {
            //TODO 关闭管道
            if(reader != null){
                try {
                    reader.close();
                }catch (IOException e){
                    throw new RuntimeException(e);
                }
            }
            if(writer != null){
                writer.close();
            }
        }
    }
}

标签:字符,writer,IO4,File,reader,new,null,TODO
From: https://www.cnblogs.com/Ashen-/p/17024870.html

相关文章