java IO流文件拷贝文件(字符流标准写法)

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;
        char [] arr=new char[1024];
        while ((ch = reader.read(arr)) != -1) {
            writer.write(arr,0,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);
                }
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/sheng-sjk/p/9833458.html