I'm trying to download a .zip
archive from a given url and unzip it to a selected location. Since the download is quite large, I tried to do it in a different thread so it doesn't freeze the entire thing, but it didn't really turn out to be a complete success... Normally, I would have just create a runnable and thread object, but now, since I'm using javafx, it gives some error. I searched online and I had to use Platform.runLater()
instead. Here's my code:
private void startTask(Label st, ListView<String> view, HashMap<String, String> hash)
{
Platform.runLater(new Runnable() {
@Override
public void run() {
runTask(st,view,hash);
}
});
}
private void runTask(Label st, ListView<String> view, HashMap<String, String> hash){
String link = hash.get(view.getSelectionModel().getSelectedItem());
File file = new File("temp.zip");
try {
FileUtils.copyURLToFile(new URL(link), file);
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zis.getNextEntry();
File newFile;
FileOutputStream fos;
String fileName;
while(zipEntry != null){
fileName = zipEntry.getName();
if(fileName.contains("##TEMP##")) continue;
if(fileName.contains("MACOSX")) continue;
newFile = new File(fileName);
fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
st.setText("Status: Ready");
}
And here's the result: A 39ko temp.zip file that appears to be corrupted. It doesn't get unzipped (Obviously). I tried many links from multiple domains, still same problem...
EDIT: Tried a different method... Same error.. New Code:
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream("download.zip");
copy(in, out, 1024);
out.close();
public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
byte[] buf = new byte[bufferSize];
int n = input.read(buf);
while (n >= 0) {
output.write(buf, 0, n);
n = input.read(buf);
}
output.flush();
}
I commented the unzipping part, still the same... Conclusion: downloading is the issue.