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
原文地址:https://www.cnblogs.com/gzgBlog/p/13624616.html