• 106.Java中IO流_字符流的异常处理


    字符流的异常处理

    public static void main(String[] args) throws Exception {
            String path1 = "c:/a.txt";
            String path2 = "c:/b.txt";
    
            copyFile2(path1, path2);
        }
    
    /**
         * 使用字符流拷贝文件,有完善的异常处理
         */
        public static void copyFile2(String path1, String path2) {
            Reader reader = null;
            Writer writer = null;
            try {
                // 打开流
                reader = new FileReader(path1);
                writer = new FileWriter(path2);
    
                // 进行拷贝
                int ch = -1;
                while ((ch = reader.read()) != -1) {
                    writer.write(ch);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                // 关闭流,注意一定要能执行到close()方法,所以都要放到finally代码块中
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (writer != null) {
                            writer.close();
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    author@nohert
  • 相关阅读:
    css概述五
    css概述四
    css概述三
    css概述二
    css概述
    Python的第三方web开发框架Django
    Python中的模块和包
    SQL语句优化
    数据库向Excel写入数据
    动态拼接sql语句
  • 原文地址:https://www.cnblogs.com/gzgBlog/p/13624616.html
Copyright © 2020-2023  润新知