2013-08-05 218 views
0

刪除文件我先發布我的代碼:不能在嘗試捕捉

private void validateXml(String xml) throws BadSyntaxException{ 
    File xmlFile = new File(xml); 
    try { 
     JaxbCommon.unmarshalFile(xml, Gen.class); 
    } catch (JAXBException jxe) { 
     logger.error("JAXBException loading " + xml); 
     String xmlPath = xmlFile.getAbsolutePath(); 
     System.out.println(xmlFile.delete()); // prints false, meaning cannot be deleted 
     xmlFile.delete(); 
     throw new BadSyntaxException(xmlPath + "/package.xml"); 
    } catch (FileNotFoundException fne) { 
     logger.error("FileNotFoundException loading " + xml + " not found"); 
     fne.printStackTrace(); 
    } 
} 

你可以在我的評論看到我打印的文件不能被刪除。文件無法從try/catch中刪除?所以,如果有一個xml語法錯誤的文件,我想刪除catch中的文件。

編輯:我可以刪除該文件,當我從此功能外使用delete()。我在Windows上。

+1

您正在使用哪種操作系統? Windows有鎖定文件的傾向,在Linux/Unix上你可能遇到權限問題。此外,它可能意味着該文件不存在。你可以使用'.exists()'來檢查嗎? –

+0

我現在在Windows上。 –

+0

只是好奇,什麼是抓住'JAXBException'堆棧跟蹤?也許這有助於確定文件是否仍然打開並且在您嘗試刪除文件時被鎖定。 – dic19

回答

1

確保此方法調用JaxbCommon.unmarshalFile(xml, Gen.class);在發生異常時關閉任何流。如果正在讀取文件的流仍處於打開狀態,則無法將其刪除。

0

該問題與try/catch無關。你有權限刪除該文件嗎?

如果您使用的是Java 7,那麼您可以使用Files.delete(Path),我認爲這將導致IOException以及無法刪除文件的原因。

+0

我會試試這個。我編輯了我的問題 –

0

在try/catch塊中使用java.io.File.delete()沒有一般限制。

許多java.io.File方法的行爲可能取決於應用程序正在運行的平臺/環境。這是因爲他們可能需要訪問文件系統資源。

例如,下面的代碼在Ubuntu 12.04返回false在Windows 7和true

public static void main(String[] args) throws Exception {  
    File fileToBeDeleted = new File("test.txt"); 

    // just creates a simple file on the file system 
    PrintWriter fout = new PrintWriter(fileToBeDeleted); 

    fout.println("Hello"); 

    fout.close(); 

    // opens the created file and does not close it 
    BufferedReader fin = new BufferedReader(new FileReader(fileToBeDeleted)); 

    fin.read(); 

    // try to delete the file 
    System.out.println(fileToBeDeleted.delete()); 

    fin.close(); 
} 

所以,真正的問題可能取決於幾個因素。但是,它與駐留在try/catch塊上的代碼無關。

也許,您試圖刪除的資源已打開,並且未被其他進程關閉或鎖定。