0

I'm having a directory which is having the folders with the name of date format.directory

I have a code to delete the folders which are in format other than the date format.Its working but throwing Exception.

My code is:

DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date dat=new Date();
        String direct="D:\\tempm\\Sample\\"+dateFormat.format(dat);
        String dirPath="D:\\tempm\\Sample\\";
        File filePath=new File(direct);
        if(!filePath.exists())
        {
            filePath.mkdir();
            System.out.println("folder created");
        }
        File dirDel=new File(dirPath);
        for(File fileDel:dirDel.listFiles())
        {

            System.out.println("files inside???"+fileDel.getName());
            Date d2 = null;
            try {
                dateFormat.setLenient(true);
                d2 = dateFormat.parse(fileDel.getName());  //throwing exception here
                System.out.println("the result is "+d2);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(d2==null)
            {
                fileDel.delete();
            }

        }

The error message is

java.text.ParseException: Unparseable date: "New folder"
    at java.text.DateFormat.parse(Unknown Source)
    at ext.gt.test.DateMod.main(DateMod.java:31)

My code is working but I need to solve that exception.Is there any other way to do this check??It'd be better to check the dateformat without regex.

4

1 回答 1

3

我建议使用正则表达式来检查文件夹是否是“日期”文件夹。您不应该使用异常来控制应用程序的常规流程。这被认为是不好的做法,因为它使遵循实际逻辑和发现用于“异常”(因此得名...)案例的代码变得更加困难。

这里进一步讨论了这个想法:为什么不使用异常作为常规控制流?

于 2013-07-26T13:11:38.760 回答