0
我有一個名稱爲日期格式的文件夾。 如何解決java.text.ParseException
我有一個代碼來刪除格式不是日期格式的文件夾。它工作但拋出異常。
我的代碼是:
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.Is有任何其他方式做此項檢查 - 它如果沒有正則表達式,最好檢查dateformat。
抓住異常? –
在這種情況下,異常是預期的行爲。實際上,目前您的代碼邏輯依賴於異常處理。只要不打印堆棧跟蹤(刪除'e.printStackTrace()'行),如果你不想在你的輸出中看到它 –
是的,我現在明白了。 –