fixed left open resources, ensured quiet closing of the streams

This commit is contained in:
Marc Zwart 2018-03-20 12:01:25 +01:00
parent 0da4e10c49
commit 9187248e85

View file

@ -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());
}
}
}
}