I’m working in a java application with Spring Boot, and in one of my UT I create a ZIP file (I check the entries…) and at the end I’m trying to delete it from my system, but what I’m trying is not working.
You can find an example of the code I’m using in the following link:
Why am I having java.io.IOException: Stream Closed in my test?
Resume of the code:
//I recover the zip
ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip");
List<String> entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
//Doing assertions...
//Deletion of the zip
File file = new File( "src/test/resources/exported_data_test.zip");
file.delete();
But at the end of the test the zip still exists on my system:
Can someone help me delete the zip file at the end of the test?
2
Best practice is to utilize the Closable/AutoCloseable
interface with a try-with-resource:
List<String> entries;
//I recover the zip
try (ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip")) {
entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
}
//Doing assertions...
//Deletion of the zip
File file = new File( "src/test/resources/exported_data_test.zip");
file.delete();
Notice, that the Zip is created inside the parenthesis of the try. After the scope following the try is exited, the program will call close upon the zip.
0
Before starting new operation on the same file, you need to close it.
Based on your example:
//I recover the zip
ZipFile zipFile = new ZipFile( "src/test/resources/exported_data_test.zip");
List<String> entries = zipFile.stream().map(ZipEntry::getName).collect(Collectors.toList())
zipFile.close(); // Added
//Doing assertions...
//Deletion of the zip
File file = new File( "src/test/resources/exported_data_test.zip");
file.delete();