Java tutorial
/* * This file is part of the InfinityCubed Launcher source code. * Copyright (C) 2014 InfinityCubed Team. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.chris54721.infinitycubed.data; import net.chris54721.infinitycubed.utils.DownloadCountingOutputStream; import net.chris54721.infinitycubed.utils.LogHelper; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.awt.event.ActionListener; import java.io.*; import java.net.URL; public class Downloadable { protected URL source; protected File target; protected long fileSize; /** If set to false, skips download if local file exists and has same size **/ protected boolean force = true; public Downloadable(URL source, File target, long fileSize) { this.source = source; this.target = target; this.fileSize = fileSize; } public Downloadable(URL source, File target) throws IOException { this(source, target, source.openConnection().getContentLengthLong()); } public URL getSource() { return source; } public File getTarget() { return target; } public long getFileSize() { return fileSize; } public void setForce(boolean force) { this.force = force; } public boolean isLocalValid() { return getTarget().isFile() && getTarget().length() == getFileSize(); } public boolean download() { return download(null); } public boolean download(ActionListener listener) { if (!force && isLocalValid()) return true; LogHelper.info("Downloading file " + target.getName()); InputStream in = null; OutputStream out = null; try { if (!target.getParentFile().isDirectory()) target.getParentFile().mkdirs(); in = source.openStream(); out = new FileOutputStream(target); if (listener != null) { out = new DownloadCountingOutputStream(getFileSize(), out); ((DownloadCountingOutputStream) out).setListener(listener); } long copied = IOUtils.copy(in, out); return copied == getFileSize(); } catch (Exception e) { LogHelper.error("Failed downloading file " + target.getName(), e); FileUtils.deleteQuietly(target); return false; } finally { if (in != null) IOUtils.closeQuietly(in); if (out != null) IOUtils.closeQuietly(out); } } }