Sonar is giving an error that this FileOutputStream
should be closed. I need to modify the following code to use try-with-resources
. How do I do this?
public void archivingTheFile(String zipFile){
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String file : this.fileList){
ZipEntry ze= new ZipEntry(file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
zos.close();
}catch(IOException ex){
LOGGER.error("Exception occurred while zipping file",ex);
}
}
The java. io. FileOutputStream. close() closes this file output stream and releases any system resources associated with this stream.
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.
Creates a file output stream to write to the file with the specified name. If the second argument is true , then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.
Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc. InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.
Currently code is not ready to handle exceptions - you're missing finally block to close open streams. And, sure, you're right - using try-with-resources solves this problem:
public void archivingTheFile(String zipFile) {
byte[] buffer = new byte[1024];
try (FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos)) {
for(String file : this.fileList) {
try (FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file)) {
ZipEntry ze = new ZipEntry(file);
zos.putNextEntry(ze);
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
}
} catch(IOException ex) {
LOGGER.error("Exception occurred while zipping file",ex);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With