java:把一个文件夹中的所有文件复制到指定文件夹下

   接受tmp1文件夹中的所有文件到tmp2文件夹中

    一个主方法和两个函数,其中一个函数要调用另外一个函数。

主方法运行
public static void main(String[] args) {
        String path2 = "C://Users//36186//Downloads//CPS-OCR-Engine-master//ocr//tmp2";
        String path1 = "C://tessrect//tmp1";
        copyFolder(path1, path2);
}
 //复制指定文件夹下的所有文件到另一个文件夹下
    public static void copyFolder(String strPatientImageOldPath, String strPatientImageNewPath) {
        File fOldFolder = new File(strPatientImageOldPath);//旧文件夹
        try {
            File fNewFolder = new File(strPatientImageNewPath);//新文件夹
            if (!fNewFolder.exists()) {
                fNewFolder.mkdirs();//不存在就创建一个文件夹
            }
            File[] arrFiles = fOldFolder.listFiles();//获取旧文件夹里面所有的文件
            for (int i = 0; i < arrFiles.length; i++) {
                //从原来的路径拷贝到现在的路径,拷贝一个文件
                if (!arrFiles[i].isDirectory()) {
                    copyFile(strPatientImageOldPath + "/" + arrFiles[i].getName(), strPatientImageNewPath + "/" + arrFiles[i].getName());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
 //复制指定文件夹下单个文件到另一个文件夹下
    public static void copyFile(String strOldpath,String strNewPath)
    {
        try
        {

            File fOldFile = new File(strOldpath);
            if (fOldFile.exists())
            {
                int bytesum = 0;
                int byteread = 0;
                InputStream inputStream = new FileInputStream(fOldFile);
                FileOutputStream fileOutputStream = new FileOutputStream(strNewPath);
                byte[] buffer = new byte[1444];
                while ( (byteread = inputStream.read(buffer)) != -1)
                {
                    bytesum += byteread; //这一行是记录文件大小的,可以删去
                    fileOutputStream.write(buffer, 0, byteread);//三个参数,第一个参数是写的内容,
                    //第二个参数是从什么地方开始写,第三个参数是需要写的大小
                }
                inputStream.close();
                fileOutputStream.close();
            }
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("复制单个文件出错");
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_33098049/article/details/88868041