Sonarcloud is reporting an error to close many InputStream objects in the finally block but it is already solved with the closeSafely(Closeable)
method.
I’m writing an Android application in Java.
These are the methods I have:
public static boolean zipFileAtPath(File sourceFile, File zipDestination) {
final int BUFFER = 2048;
Log.d(TAG, "Zipping " + sourceFile + " into " + zipDestination);
ZipOutputStream out = null;
FileOutputStream dest = null;
BufferedInputStream origin = null;
FileInputStream fi = null;
try {
dest = new FileOutputStream(zipDestination);
out = new ZipOutputStream(new BufferedOutputStream(dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
fi = new FileInputStream(zipDestination);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(zipDestination.getPath()));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
} catch (Exception e) {
Mint.logException(e);
Log.d(TAG, "Exception:", e);
return false;
} finally {
closeSafely(out);
closeSafely(dest);
closeSafely(origin);
closeSafely(fi);
}
return true;
}
private static void closeSafely(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
Log.e(TAG, "closeSafely: ", e);
}
}
}
This screenshot shows the error in Sonarcloud
Thanks for explanations