Beispiel #1
0
  /**
   * Lädt über eine URLConnection eine Datei herunter. Zieldatei ist file.
   *
   * @param file
   * @param con
   * @return Erfolg true/false
   * @throws IOException
   */
  public static void download(final File file, final HTTPConnectionImpl con) throws IOException {
    if (file.isFile()) {
      if (!file.delete()) {
        System.out.println("Konnte Datei nicht löschen " + file);
        throw new IOException("Could not overwrite file: " + file);
      }
    }

    final File parentFile = file.getParentFile();
    if (parentFile != null && !parentFile.exists()) {
      parentFile.mkdirs();
    }
    file.createNewFile();
    FileOutputStream fos = null;
    BufferedOutputStream output = null;
    BufferedInputStream input = null;
    boolean okay = false;
    try {
      output = new BufferedOutputStream(fos = new FileOutputStream(file, false));
      input = new BufferedInputStream(con.getInputStream());
      final byte[] b = new byte[1024];
      int len;
      while ((len = input.read(b)) != -1) {
        output.write(b, 0, len);
      }
      okay = true;
    } finally {
      try {
        output.close();
      } catch (final Throwable e) {
      }
      try {
        input.close();
      } catch (final Throwable e) {
      }
      try {
        fos.close();
      } catch (final Throwable e) {
      }
      if (okay == false) {
        file.delete();
      }
    }
  }