用java写一个简单的文件拷贝程序吧

代码:

    public static void copyFile(String srcPath, String destPath) throws IOException {
        //建立File对象的来源与目的
        File src = new File(srcPath);
        File dest = new File(destPath);
        
        //由于只能拷贝文件,所以判定输入流是否为文件
        if(!src.isFile()) {
            System.out.println("只能拷贝文件!");
            throw new IOException("只能拷贝文件!");
        }
        
        //文件输入输出
        InputStream is = new FileInputStream(src);
        OutputStream os = new FileOutputStream(dest);
        
        //读取文件大小,并循环写出文件
        byte[] flush = new byte[1024];
        int len = 0;
        while(-1 != (len = is.read(flush))) {
            os.write(flush, 0, len);
        }
        
        //刷新此输出流并强制写出所有缓冲的输出字节
        os.flush();
        
        //释放资源(一般先打开的后关闭)
        os.close();
        is.close();
        
        System.out.println("拷贝成功!");
    }

 

posted @ 2017-04-02 14:28  NOthingAJ  阅读(664)  评论(0编辑  收藏  举报