2013-07-26 147 views
0

我有一個名稱爲日期格式的文件夾。 directory如何解決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。

+0

抓住異常? –

+1

在這種情況下,異常是預期的行爲。實際上,目前您的代碼邏輯依賴於異常處理。只要不打印堆棧跟蹤(刪除'e.printStackTrace()'行),如果你不想在你的輸出中看到它 –

+0

是的,我現在明白了。 –

回答

3

我建議使用正則表達式來檢查文件夾是否是「日期」文件夾。您不應該使用異常來控制應用程序的正常流程。這被認爲是不好的做法,因爲它使得難以遵循實際的邏輯並發現用於「例外」(因此名稱......)情況的代碼。

這個想法在這裏進一步討論:Why not use exceptions as regular flow of control?