从文件夹中复制指定的文件到另一个文件夹

1、以下方法均在A类中

/**
*localPath:源文件夹的路径
*filterIrpFileFolderPath:存放复制后的文件的路径
*fileType:过滤要复制的文件的条件
*/
private
void filterIrpFiles(String localPath, String filterIrpFileFolderPath, String fileType) { if (StringUtil.isEmpty(localPath) || StringUtil.isEmpty(filterIrpFileFolderPath)) { return; } File folder = new File(localPath); if (!folder.exists()) { return; } File[] files = folder.listFiles(); if (null == files) { return; } // 创建文件夹 File dir = new File(filterIrpFileFolderPath); if (!dir.exists()) { dir.mkdirs(); } for (File file : files) { if (!file.isFile()) { continue; } if (!file.getName().trim().contains(fileType)) { continue; } copyFile(filterIrpFileFolderPath, file); } }
private void copyFile(String filterIrpFileFolderPath, File file)
    {
        InputStream is = null;
        OutputStream os = null;
        try
        {
            File osFile = new File(filterIrpFileFolderPath + File.separator + file.getName().trim());
            if (!osFile.exists())
            {
                osFile.createNewFile();
            }
            is = new FileInputStream(file);
            os = new FileOutputStream(osFile);
            byte[] flush = new byte[1024];
            int len = -1;

            while((len = is.read(flush)) != -1)
            {
                os.write(flush, 0, len);
            }
       // 刷新缓存
            os.flush();
        }
        catch (IOException e)
        {
            logger.error(e);
        }
        finally
        {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }

TEST:

public static void main(String[] args)
{
    A a= new A();
    a.filterIrpFiles("D:\\AX_EDI\\HaviToGodiva", "D:\\EC_EDI\\HaviToGodiva", "DC");
}

 

posted @ 2020-03-18 08:56  Aj小菜  阅读(1401)  评论(0编辑  收藏  举报