Question

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.

Was it helpful?

Solution

I'd recommend to use a regular expression to check if the folder is a "date" folder. You shouldn't use exceptions to control the regular flow of your application. This is considered bad practice as it makes it harder to follow the actual logic and spot the code that is used for "exceptional" (hence the name...) cases.

This idea is further discussed here: Why not use exceptions as regular flow of control?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top