Reputation: 119
A few weeks ago I posted that issue here. Now I have a similiar problem with a different case. I created a java upload, where I wanted to check if a XML file is well formed. After the check, I want to delete it. But if the transformation failed, I cannot delete the file. I created a much easier example to run it on my local computer where I had the same issue. Please see below for my source code. You can easily copy and paste it and try it by yourself.
Did I uncover a bug, maybe the same bug I reported a few weeks before, or did I miss something in the code? I used Saxon 9.4HE.
public class TestClass
{
public static void main (String[] args) throws Exception
{
boolean isWellFormed = isXMLwellformed(new File("work/file.xml"));
if(isWellFormed) System.out.println("File is well formed");
else
{
System.out.println("File is not well formed");
}
FileUtils.deleteDirectory(new File("work"));
}
private static boolean isXMLwellformed(File file)
{
boolean isWellformed = true;
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource source = new StreamSource(file);
try
{
Transformer trans = factory.newTransformer();
SAXResult sink = new SAXResult(new DefaultHandler());
trans.transform(source, sink);
}
catch (TransformerException err)
{
System.err.println("Validation failed: " + err.getMessage());
isWellformed = false;
}
return isWellformed;
}
}
Upvotes: 0
Views: 250
Reputation: 119
Now, I find a solution that works. If I create the FileReader on my own and close it in the catch block, it works. But shouldn't it be closed automatically?
private static boolean isXMLwellformed(File file) throws IOException
{
boolean isWellformed = true;
BufferedReader br = new BufferedReader(new FileReader(file));
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource source = new StreamSource(br);
try
{
Transformer trans = factory.newTransformer();
SAXResult sink = new SAXResult(new DefaultHandler());
trans.transform(source, sink);
}
catch (TransformerException err)
{
System.err.println("Validation failed: " + err.getMessage());
br.close();
isWellformed = false;
}
return isWellformed;
}
Upvotes: 1