2013-08-05 159 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块上的代码无关。

也许,您试图删除的资源已打开,并且未被其他进程关闭或锁定。