我有一个目录,其中包含名称为日期格式的文件夹。
我有一个代码可以删除日期格式以外的文件夹。它可以工作,但会抛出异常。
我的代码是:
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/