Пример #1
0
  /** Unpacks a resource to a temp. file */
  public static File unpackInstaller(String resourceName) {
    // Array to hold all results (this code is slightly more
    // generally that it needs to be)
    File[] results = new File[1];
    URL[] urls = new URL[1];

    // Determine size of download
    ClassLoader cl = Main.class.getClassLoader();
    urls[0] = cl.getResource(Config.getInstallerResource());
    if (urls[0] == null) {
      Config.trace("Could not find resource: " + Config.getInstallerResource());
      return null;
    }

    int totalSize = 0;
    int totalRead = 0;
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        try {
          URLConnection connection = urls[i].openConnection();
          totalSize += connection.getContentLength();
        } catch (IOException ioe) {
          Config.trace("Got exception: " + ioe);
          return null;
        }
      }
    }

    // Unpack each file
    for (int i = 0; i < urls.length; i++) {
      if (urls[i] != null) {
        // Create temp. file to store unpacked file in
        InputStream in = null;
        OutputStream out = null;
        try {
          // Use extension from URL (important for dll files)
          String extension = new File(urls[i].getFile()).getName();
          int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1;
          if (lastdotidx == -1) {
            extension = ".dat";
          } else {
            extension = extension.substring(lastdotidx);
          }

          // Create output stream
          results[i] = File.createTempFile("jre", extension);
          results[i].deleteOnExit();
          out = new FileOutputStream(results[i]);

          // Create inputstream
          URLConnection connection = urls[i].openConnection();
          in = connection.getInputStream();

          int read = 0;
          byte[] buf = new byte[BUFFER_SIZE];
          while ((read = in.read(buf)) != -1) {
            out.write(buf, 0, read);
            // Notify delegate
            totalRead += read;
            if (totalRead > totalSize && totalSize != 0) totalSize = totalRead;

            // Update UI
            if (totalSize != 0) {
              int percent = (100 * totalRead) / totalSize;
              setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent));
            }
          }
        } catch (IOException ie) {
          Config.trace("Got exception while downloading resource: " + ie);
          for (int j = 0; j < results.length; j++) {
            if (results[j] != null) results[j].delete();
          }
          return null;
        } finally {
          try {
            if (in != null) in.close();
            if (out != null) out.close();
          } catch (IOException io) {
            /* ignore */
          }
        }
      }
    }

    setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK));
    return results[0];
  }