java - 如何解决java.text.ParseException

标签 java date simpledateformat parseexception

我有一个目录,其中包含名称为日期格式的文件夹。 directory

我有一个代码可以删除日期格式以外的文件夹。它可以工作,但会抛出异常。

我的代码是:

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();
            }

        }

错误信息是

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

我的代码可以正常工作,但我需要解决该异常。还有其他方法可以进行此检查吗?最好在没有正则表达式的情况下检查日期格式。

最佳答案

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

这个想法在这里进一步讨论:Why not use exceptions as regular flow of control?

关于java - 如何解决java.text.ParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17882116/

相关文章:

java - Jetty 和 Java 代理无法使用日志记录工作

MySql 字符到日期格式转换返回 null

mysql - 按开始和/或结束日期对 MySQL 中的事件进行排序

javascript - 将日期文本(字符串)更改为日期格式 Javascript

java - 简单日期格式间歇性地返回错误日期

java - 需要一些帮助!

java - 使用 Spring Security 进行 Spring Boot 2 测试

java - 计算字符串数组中每个元素的数量

java - SimpleDateFormat 始终返回 12.30 AM

java - JdateChooser 中的格式化程序