fixed left open resources, ensured quiet closing of the streams
@@ -4,7 +4,7 @@ import java.io.*;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
-
+import java.io.Closeable;
/**
* Helper for file operations.
*
@@ -84,15 +84,17 @@ public final class FileHelper {
*/
public static void downloadFile(String filename, HttpURLConnection urlConnection) {
System.out.println("Downloading " + filename);
+ InputStream in = null;
+ FileOutputStream out = null;
try {
- InputStream in = urlConnection.getInputStream();
+ in = urlConnection.getInputStream();
File f = new File(filename);
if (!f.exists() && f.getParentFile() != null) {
f.getParentFile().mkdirs();
System.out.println("Directories have been created: " + f.getParentFile().getPath());
}
- FileOutputStream out = new FileOutputStream(filename);
+ out = new FileOutputStream(filename);
byte[] buf = new byte[4 * 1024];
int bytesRead;
@@ -103,6 +105,19 @@ public final class FileHelper {
System.out.println("File has been updated: " + filename);
} catch (IOException e) {
System.out.println("i/o exception - " + e.getMessage());
+ } finally {
+ closeQuietly(in);
+ closeQuietly(out);
+ }
+ }
+
+ public static void closeQuietly(Closeable s) {
+ if(s != null) {
+ try {
+ s.close();
+ } catch (Exception e) {
+ System.out.println("i/o exception - " + e.getMessage());
+ }
}
}
}
