java中如何复制文件

来源:互联网 发布:周立功单片机应用技巧 编辑:程序博客网 时间:2024/06/06 16:39

需要用到文件输入流FileInputStream,文件输出流FileOutputStream

public static void copyFolder(String oldfilename,String newfilename) throws IOException {

        File of=new File(oldfilename);
        if(of.exists()) {
            try {
                InputStream is=new FileInputStream(of);
                FileOutputStream out=new FileOutputStream(newfilename);
                byte[] data=new byte[20480];

                int len=0;

                   //长度如果是-1那么读取完毕,开始写入

                    while((len=is.read(data))!=-1){
                        out.write(data,0,len);
                    }
            //复制完毕,手动刷新缓冲区,关闭流,节省资源
                out.flush();
                is.close();
                out.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("复制失败");
            }
        }
    }
原创粉丝点击